4imble
4imble

Reputation: 14426

Setting var to sum of two textbox values is 0, how come?

I am experiencing something odd, please see below. Why is alert 1 outputting 0 but alert 2 outputting the correct sum? They are set to the same thing...

var sumTotal = parseFloat($('#tb1').val()) + parseFloat($('#tb2').val());
//tb1.val() == 3, tb2.val() == 5;    

1) alert(sumTotal); //Outputs 0;
2) alert(parseFloat($('#tb1').val()) + parseFloat($('#tb2').val())); //Outputs 8;

Exact code:

    $(document).ready(function () {
        var koh = 1;
        var sumTotal = parseFloat($('#tb1').val()) + parseFloat($('#tb2').val());
        window.setInterval(function () {
            // correct value
            tb3.val(parseFloat($('#tb1').val()) + parseFloat($('#tb2').val())); 
            tb3.val(parseFloat(sumTotal)); // 0
            tb3.val(sumTotal); // 0
            tb3.val(koh++) //increments +1
        }, 2500);
    })

since koh increments +1 can this still be a scoping issue?

Upvotes: 0

Views: 1257

Answers (2)

Utaal
Utaal

Reputation: 8534

Try removing the call to parseFloat, so this line

tb3.val(parseFloat(sumTotal));

becomes

tb3.val(sumTotal);

In fact, sumTotal is already a float (you've converted it before summing):

var sumTotal = parseFloat($('#tb1').val()) + parseFloat($('#tb2').val());

and using parseFloat on a float value will probably lead to undefined behaviour.


I think I spotted it: the value in the textboxes is prepopulated in html?

If the textboxes are empty or contain 0 at this point

var sumTotal = parseFloat($('#tb1').val()) + parseFloat($('#tb2').val());

the value stored in sumTotal will be NaN or 0 respectively (thanks to cHao for pointing this out) and it won't change from then on: remember that the statement tb3.val(sumTotal); won't re-evaluate sumTotal.

If you wanted to update the sum on user input you'll need something like:

$(document).ready(function () {
    var sumTotal = parseFloat($('#tb1').val()) + parseFloat($('#tb2').val());
    $('#tb1').add('#tb2').keyup(function () {
        sumTotal = parseFloat($('#tb1').val()) + parseFloat($('#tb2').val());
        tb3.val(sumTotal);
    });
})

Upvotes: 0

cHao
cHao

Reputation: 86575

sumTotal is calculated before the values of the text boxes have changed. If they default to 0, the result will be 0, and it won't change even if the text boxes' values do.

If they default to blank, sumTotal is NaN -- and it still won't change.

Upvotes: 1

Related Questions