Tips on creating an onclick function in javaScript and linking it to innerHTML

     let a = 10;
     let b = 15;
     document.getElementById("text").innerHTML = '<div 
     onclick=\'testing("'a + '","' + b + '") > text  </div>';

Welcome, I am new to this platform and struggling with the syntax for passing parameters between JavaScript and HTML functions. Can someone help me achieve something similar to onclick='testing(a,b)'? Thank you!

Answer №1

Are you attempting to update the content of your #text element with the result of test(x,y)? To achieve this, you would typically use code similar to:

const answer = test(x,y);
document.getElementById('idOfThingToBeChanged').innerHTML = answer;

If you want this action to occur when a button is clicked on your page, you should include this code within your event listener, like so:

document.getElementById('idOfThingToBeClicked')
   .addEventListener('click', () => {
      // (the code above)
   });

If X and Y are values obtained from elements in your HTML page, you can retrieve them as follows:

const x = document.getElementById('idOfElement1').value;
const y = document.getElementById('idOfElement2').value;
const answer = test(x, y);

This will lead to your final solution resembling something like:

document.getElementById('elementToBeClicked')
   .addEventListener('click', () => {
      const x = document.getElementById('idOfElement1').value;
      const y = document.getElementById('idOfElement2').value;
      document.getElementById('elementToBeChanged')
         .innerHTML = test(x, y);
});
//Make sure to add this code after the page has loaded

I hope this explanation covers all aspects, but feel free to reach out if you need further assistance.

Answer №2

function demonstrate(a,b){
alert(a, b);
}

var a = 20
     var b = 30
     document.getElementById("content").innerHTML = `<div onclick="demonstrate(${a},${b})"> message</div>`;
 <div id="content"></div>

Note: The function demonstrate will display an alert to confirm that it is functioning correctly

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The clash between Traditional JavaScript and jQuery

As I pored over a textbook, I found myself stumped by an example problem. Here is the HTML code in question: $(function(){ $("#checkAll").click(function(){ $("[name=items]:checkbox").attr("checked", true); console.log("check all"); }); $("#checkNo").cl ...

Obtain the JSON data from the body of the current post request in Express.js

I have been working on retrieving the actual request body JSON in express.js but haven't been successful so far. Most of the resources I found online only show how to access the body of type ReqBody, whereas I am looking for a way to retrieve the actu ...

Ways to dynamically toggle visibility and hide elements by clicking outside the specified div

I have a div that, when clicked, displays a contact us form. This form toggles between being visible and hidden. How can I make it hide when clicked on another part of the document? Here is the code: function showContactForm(){ var formWidth = &apos ...

Retrieving an array from the $.get() method within multiple nested loops

I'm currently working on a jQuery plugin that takes an array of JSON files and needs to compile them into one large array. While each part of the code works individually, I'm facing issues when trying to integrate them together and return the ne ...

Retrieve the temporary file path using JavaScript/jQuery

Here is the code snippet: <div> <label class="control-label" for="Name">Add XML</label> </div> <div> <input id='upload' name="upload[]" type="file" accept=".xml"/> </div> <script src="//c ...

Leverage the power of the modal component in your ReactJS

I'm facing an issue with the antd library. Even after installing it from the official site and importing the modal component, it's not functioning properly for me. I've carefully checked everything in my code and everything seems to be fine. ...

Error in Redux app: Attempting to access the 'filter' property of an undefined value

I am currently encountering an issue with my reducer: https://i.stack.imgur.com/7xiHJ.jpg Regarding the props actual, this represents the time of airplane departure or arrival, and it is a property within my API. The API structure looks like this: {"body ...

Frames of Animation

Seeking assistance in understanding how to create frame animation using JavaScript or CSS. Attempting to replicate the animation seen on this website. Intrigued by the road animation and unsure if it is achieved using a plugin or just JavaScript and CSS. ...

Whenever I attempt to execute yarn build within next.js, an error always seems to occur

When attempting to compile my next.js project using the yarn build command, an error consistently occurs: Error: Export encountered errors on following paths: /settings at D:\web3\futnft\frontend\node_modules\next\ ...

Why am I seeing numbers in the output when I log the data from the res.write(data) function in Node.js?

While working with Node.js on my Raspberry Pi, I encountered an issue where reading a local file 'test.html' resulted in hex output instead of the expected HTML format. Can someone explain why this might be happening? Additionally, I am aware tha ...

What methods can be used to ensure that the variable $ can serve as both an object and a function?

One interesting feature of jQuery is how the variable $ can function as both an object and a function. // For example, you can access object properties like $.fn; // or $.isReady; // You can also call the function $ like this $(); So, how can we make the ...

What is the method of using "*" as the value for allowedModules in a jsreport configuration file to enable all modules?

I am having an issue when trying to generate a report using jsreport STUDIO. The error message I received is as follows: An error occurred - Error during rendering report: Unsupported module in scripts: request. To enable require on a particular module, ...

Having trouble inputting text into the text area using Selenium WebDriver with C#

Here is the original code snippet: I am having trouble entering text in the text box below. Can you please help me figure out how to enter text in this text box? <td id="ctl00_cRight_ucSMS_redSMSBodyCenter" class="reContentCell" ...

What is the purpose of assigning scope.property to scope.property() in order for the expression to function properly?

I have encountered an interesting situation with the directive below. In order for my expressnum function to work in the template, I had to include the line scope.expressnum = scope.expressnum();. It does what I need it to do, but I'm not entirely sur ...

What is the best way to create a JavaScript function that can be used for multiple expandable cards in HTML and CSS?

I'm dealing with a situation where I have a list of cards, and I want to be able to expand the content individually when clicking on "more info". Can someone offer advice on how to achieve this using Javascript? Check out this CodePen for reference: ...

Is there a way to eliminate the surplus 2 download icons from this Angular code when there are a total of 3 users?

Here is some HTML code snippet: <tr *ngFor="let user of users"> <td> <h6 class="font-medium">{{user.id}}</h6> </td> <td> <h ...

Successive promises of catches

Here is a situation that I am dealing with: controller.ts methodA(): void { myServive.someMethod() .then( () => console.log("then") ) .catch( e => { console.log("catch"); }); } service.ts someMethod(): ng: ...

Creating movement effects for a line on an HTML5 canvas following a previous animation

I am facing an issue where my straight line starts animating towards the circle right at the beginning of page load. I am struggling with finding the logic to make the line animate in the opposite direction after the first animation is completed (which is ...

Limit the options in jQuery UI auto-complete to search by name from a variety of JSON responses

I am looking to enhance my search functionality by utilizing jqueryUi's auto-complete feature to specifically target Names and exclude other array values such as fax. Here is how I have implemented it in php: <?php require_once 'db_conx.php&a ...

Error: FileReader is not defined in Node.js (Nest.js) environment

I am working on converting my image to base64 using a custom function. However, when I try to execute the code, I encounter an error message stating ReferenceError: FileReader is not defined. This error has left me puzzled and unsure of its cause. Below i ...