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:
You can get the values with use of ID
. But ID
should be Unique.
<body>
<h1>Adding 'a' and 'b'</h1>
<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() {
a = $('#a').val();
b = $('#b').val();
var sum = a + b;
alert(sum);
}
</script>
</body>
<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>
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>
do you use jquery? if then:
$('#xx').val();
or use original javascript(DOM)
document.getElementById('xx').value
or
xxxform.xx.value;
if you want to learn more, w3chool can help you a lot.
Use this it will work,
<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()">Add</button>
</form>
<script>
function add() {
var m = document.getElementById("a").value;
var n = document.getElementById("b").value;
var sum = m + n;
alert(sum);
}
</script>
</body>
<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>