Why is my jQuery incorrectly adding values ​​in each loop?

I try to get the values ​​of several fields and add them together, and during testing I am having problems. I have this code:

var count;

function calculate() {

    // Fix jQuery conflicts
    jQuery.noConflict();

    count = 0;

    jQuery('.calculate').each(function() {

        var currentElement = jQuery(this);

        var value = currentElement.val();

        var count = count + value;

        alert(count);

    });

}

I entered the value "9" in my first field, and when the first warnings fire, I get "undefined9"; all other values ​​are currently set to "0"; when it fires again, I always get "undefined0".

Why do I get the "undefined" bit and why does it only return the current field and not add them together?

+3
source share
3 answers

You measure the value countinside the loop, essentially setting it to undefinedfirst at each iteration.

var . , , JavaScript .

parseInt(count, 10) , JavaScript + , , count "0something".

, count += value :)

+6

count:

var count = count + value;

:

count = count + value;

, (calculate), ( "" ).

, "undefined9", , count undefined; , undefined , , , "undefined9".

, + , , ; .

+5

You define the score in two different areas - the calculation function, and then in the function that everyone uses. You may want the second account to be called something else, or at least not update it.

0
source

All Articles