How to Pass a Variable to JavaScript

104 30
    • 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.

Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.