How to Pass a Variable to JavaScript
- 1). Write the function that is going to have variables passed to it. A sample function that generates an alert might look something like:
function myfunction(txt)
{
alert(txt);
}
If this is inside of an HTML page, this code should be enclosed in "script" tags; do this in your favorite text editor. - 2). Create an HTML button. The following code is an example of what HTML button code looks like.
<input type="button" value="Call function"> - 3). Add the following code to the button code:
onclick="myfunction('Hello')"
This code should go between the "type" and "value" parameters. This is the code that calls the function that was defined and passes it a variable. - 4). Save the document. It should end in ".html." Open the file and click the button to see the effect of passing a variable to this JavaScript function.