jQuery adding 2 numbers from input fields
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.
<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>