Pass parameter to JavaScript function onclick in HTML | Example code

It’s very easy to Pass parameter to JavaScript function using the onClick() function. If sending a string value then use double” ” or single ” quote in the function.

1. Example Pass string parameter in onClick function

You just need to add some quotes around the text. Using input button for this example:-

<!DOCTYPE html>
<html>
<head>
   <script type="text/javascript">
       function dosomething(val){
          alert(val);
      }
  </script>

</head>
<body>
    <input type="button" value="Click" onclick="dosomething('Hello')">
</body>
</html>

Output:

Pass string parameter in onClick function

2. Example Passing integer values to JavaScript onClick()

Now pass integer value but this time we are using an <a> anchor tag (link) to passing the value.

You can call a function and pass the integer as parameter.

<!DOCTYPE html>
<html>
<head>
 <script type="text/javascript">
  function yourFunction(intValue){
     alert(intValue);
 }
</script>

</head>
<body>
   <a href="#"  onclick="yourFunction('1')">click1</a>
   <a href="#"  onclick="yourFunction('2')">click2</a>
</body>
</html>

Output:

Passing integer values to JavaScript onClick

3. Example Passing parameters in javascript onclick event

Example of How to Pass Parameter in JavaScript Function From Html elements:-

JavaScript function multiple parameters adding. (Adding 2 numbers in JS).

<!DOCTYPE html>
<html>
<head>

</head>
<body>
    <body>
        <h1>Adding 'a' and 'b'</h1>

        a: <input type="number" name="a" id="a"><br>
        b: <input type="number" name="b" id="b"><br>
        <button onclick="add(document.getElementById('a').value,document.getElementById('b').value)">Add</button>

        <script>
          function add(a,b) {
            var sum = parseInt(a) + parseInt(b);
            alert(sum);
        }
    </script>
</body>
</body>
</html>

Output:

 Pass Parameter in JavaScript Function From Html

Do comment if you need any help or have suggestion for this topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.