Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery adding 2 numbers from input fields

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);         
    })
})
like image 904
Rhys Heredia Avatar asked Apr 29 '13 00:04

Rhys Heredia


People also ask

What is $() in jQuery?

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.

How do I get the sum of two numbers in JavaScript?

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.


1 Answers

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.

like image 170
Blender Avatar answered Sep 23 '22 21:09

Blender