Passing HTML input value as a JavaScript Function Parameter
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>
1 IDs are meant to be unique
2 You dont need to pass any argument as you can call them in your javascript
<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 = a + b;
alert(sum);
}
</script>
<form action="" onsubmit="additon()" name="form1" id="form1">
a: <input type="number" name="a" id="a"><br>
b: <input type="number" name="b" id="b"><br>
<input type="submit" value="Submit" name="submit">
</form>
<script>
function additon()
{
var a = document.getElementById('a').value;
var b = document.getElementById('b').value;
var sum = parseInt(a) + parseInt(b);
return sum;
}
</script>