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").val();
var b = $("#b").val();
$("submit").on("click", function(){
var sum = a + b;
alert(sum);
})
})
The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s). Basic syntax is: $(selector).action() A $ sign to define/access jQuery. A (selector) to "query (or find)" HTML elements.
const num1 = parseInt(prompt('Enter the first number ')); const num2 = parseInt(prompt('Enter the second number ')); Then, the sum of the numbers is computed. const sum = num1 + num2; Finally, the sum is displayed.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With