eazyduzit100
eazyduzit100

Reputation: 13

Jquery loop issue

I am attempting to loop through my array elements, find the sum of them and update a div with the value.

For some reason, my each() loop doesn't work as expected. For example, when I enter 12, 3 times, the answer should be 36, but I get 72.

Any suggestions, thanks!

View full code here: http://jsfiddle.net/lakesmaa/DGPST/3/

 $.each(array, function() { 
       sum += parseInt(this);  


    }); 
    $('.total').html(sum); 

    };

Upvotes: 1

Views: 115

Answers (5)

Rohit Jain
Rohit Jain

Reputation: 213223

On every click of button, you are adding the item to the array:

array.push(newItem);   

then iterating over the array, and adding each item to sum.

So, on 1st click:

array = [12], sum = 12

on 2nd click:

array = [12, 12], sum = (12 + 12 + 12) = 36

on 3rd click:

array = [12, 12, 12], sum = 36 + 12 + 12 + 12 = 72

Either you reset the sum inside your function to 0:

$('#button').click(function() { 
    var sum = 0;  // reset

jsFiddle Demo

Or, add the item directly, without iterating over the array:

array.push(newItem);   
sum += parseInt(newItem);

// Remove the for each loop iterating over the array to accumulate sum

jsFiddle Demo

Upvotes: 2

Moob
Moob

Reputation: 16184

You need to reset sum before the loop and pass the value to the $(each) callback like so: http://jsfiddle.net/DGPST/17/

Upvotes: 0

Bergi
Bergi

Reputation: 664297

You want to reset the sum to zero each time before summing up the array values. Currently you have just one global variable to which you add all values when clicking the button.

var sum = 0;
$.each(array, function() { 
    sum += parseInt(this);  
}); 
$('.total').html(sum); 

(demo with tidyed-up code).

Upvotes: 0

bfavaretto
bfavaretto

Reputation: 71908

You never reset the sum inside your click handler, so on every click you start from where you left.

You need:

// ...
$('#button').click(function() { 
    var sum = 0; 
    // ...
});

http://jsfiddle.net/DGPST/9/

Upvotes: 1

Mark Pieszak - Trilon.io
Mark Pieszak - Trilon.io

Reputation: 66961

That is because you are using this within your $.each(), which is expecting & trying to parse a jQuery wrapped element.

this in your instance is actually String {0: "1", 1: "2"} (console.log it and you'll see)

Instead use the item (2nd parameters) of the .each() callback function.

$.each(array, function(index, item) { 
    sum += parseInt(item);    
}); 

This will intern give you, 36 when 12 is entered 3 times, as intended.

jsFiddle Demo

Upvotes: 0

Related Questions