views:

63

answers:

2

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?

A: 

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);
    });
})
Utaal
opps. yeah i had it without, i tried adding it to see if it helped. It made no difference either way.
Kohan
Empty strings become NaN when parsed as floats.
cHao
cHao, it seems we had the same idea. By the way, thank you for pointing this out.
Utaal
+1  A: 

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.

cHao
haha, of course. What a rookie mistake. many thanks.
Kohan