Question

When using a JQuery .each function i seem to be achieving a result i am confused by.

I am expecting the total to output the sum of all of the numbers within the <span class='count'></span>

But instead theres a number that appears but i cannot see why. The numbers in the span element appear to not be considered at all.

JSfiddle

The HTML

<span class='count'>1</span>
<span class='count'>2</span>
<span class='count'>3</span>
<button id='button'>Go</button>
<hr />

<span>Total: </span><span id='total'></span>

The JQuery

$("#button").click( function(total) {
    var total = 0;

    $('.count').each( function(total) {
        var content = $(this).text();
          //alert(content);
        num = parseInt(content);
         // alert(num);
        var newtotal = total + num;

         $('#total').html(total);
    });
});
Was it helpful?

Solution

Are you expecting 6 ?

$("#button").click( function(total) {
     var newtotal=0,total = 0;

    $('.count').each( function() {
        var content = $(this).text();
          //alert(content);
        num = parseInt(content);
         // alert(num);
         newtotal +=num;

         $('#total').html(newtotal);
    });
});

http://jsfiddle.net/prollygeek/H3t5L/2/

OTHER TIPS

you're re-assigning the value of total with the index of .each()

change

$('.count').each( function(total) {

to

$('.count').each( function() {
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top