Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing HTML input value as a JavaScript Function Parameter

Tags:

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> 
like image 944
cdalto Avatar asked Jan 28 '14 05:01

cdalto


2 Answers

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>
like image 97
Ankit Avatar answered Oct 01 '22 12:10

Ankit


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> 
like image 36
dcodesmith Avatar answered Oct 01 '22 11:10

dcodesmith