I am trying to add two values of alert boxes but I keep getting a blank alert box. I don\'t know why.
$(document).ready(function(){
var a = $(\"#a\").va
<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>
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.
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);
Use this code for adding two numbers by using jquery
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>HTML Tutorial</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<meta charset="windows-1252">
<script>
$(document).ready(function(){
$("#submit").on("click", function(){
var a = parseInt($('#a').val());
var b = parseInt($('#b').val());
var sum = a + b;
alert(sum);
})
})
</script>
</head>
<body>
<input type="text" id="a" name="option">
<input type="text" id="b" name="task">
<input id="submit" type="button" value="press me">
</body>
</html>
Ok so your code actually works but what you need to do is replace a and b in your click function with the jquery notation you used before the click. This will ensure you have the correct and most up to date values. so changing your click function to this should work:
$("submit").on("click", function(){
var sum = $("#a").val().match(/\d+/) + $("#b").val().match(/\d+/);
alert(sum);
})
or inlined to:
$("submit").on("click", function(){
alert($("#a").val().match(/\d+/) + $("#b").val().match(/\d+/));
})
This code works, can you compare it with yours?
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>HTML Tutorial</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<meta charset="windows-1252">
<script>
$(document).ready(function(){
var a = $("#a").val();
var b = $("#b").val();
$("#submit").on("click", function(){
var sum = a + b;
alert(sum);
})
})
</script>
</head>
<body>
<input type="text" id="a" name="option">
<input type="text" id="b" name="task">
<input id="submit" type="button" value="press me">
</body>
</html>