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>
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>
Firstly an elements ID should always be unique. If your element IDs aren't unique then you would always get conflicting results. Imagine in your case using two different elements with the same ID.
<form> a: <input type="number" name="a" id="a"><br> b: <input type="number" name="b" id="b"><br> <button onclick="add()">Add</button> </form> <script> function add() { var a = document.getElementById('a').value; var b = document.getElementById('b').value; var sum = parseInt(a) + parseInt(b); alert(sum); } </script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With