Skip to content
Advertisement

Passing HTML input value as a JavaScript Function Parameter

I am new to JavaScript, and I’m trying to figure out how to pass user-inputted values as a parameter to a JavaScript function. Here is my code:

<body>
<h1>Adding 'a' and 'b'</h1>
<form>
  a: <input type="number" name="a" id="a"><br>
  b: <input type="number" name="b" id="a"><br>
  <button onclick="add(a,b)">Add</button>
</form>
<script>
  function add(a,b) {
    var sum = a + b;
    alert(sum);
  }
</script>
</body>

Advertisement

Answer

One way is by using document.getElementByID, as below –

<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, 10) + parseInt(b, 10);
      alert(sum);
    }
  </script>
</body>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement