jQuery adding 2 numbers from input fields
Solution 1:
Adding strings concatenates them:
> "1" + "1"
"11"
You have to parse them into numbers first:
/* parseFloat is used here.
* Because of it's not known that
* whether the number has fractional places.
*/
var a = parseFloat($('#a').val()),
b = parseFloat($('#b').val());
Also, you have to get the values from inside of the click handler:
$("submit").on("click", function() {
var a = parseInt($('#a').val(), 10),
b = parseInt($('#b').val(), 10);
});
Otherwise, you're using the values of the textboxes from when the page loads.
Solution 2:
<script type="text/javascript">
$(document).ready(function () {
$('#btnadd').on('click', function () {
var n1 = parseInt($('#txtn1').val());
var n2 = parseInt($('#txtn2').val());
var r = n1 + n2;
alert("sum of 2 No= " + r);
return false;
});
$('#btnclear').on('click', function () {
$('#txtn1').val('');
$('#txtn2').val('');
$('#txtn1').focus();
return false;
});
});
</script>
Solution 3:
There are two way that you can add two number in jQuery
First way:
var x = parseInt(a) + parseInt(b);
alert(x);
Second Way:
var x = parseInt(a+2);
alert(x);
Now come your question
var a = parseInt($("#a").val());
var b = parseInt($("#b").val());
alert(a+b);