Jitender
Jitender

Reputation: 7971

How to sum a value in array using jquery

I want to push and plus value in array. I tried it but it is giving 'NaN'. I think it can be done by defining array type to integer. Can it is possible. Fiddle here.

var total=[];
$('.check').each(function(index, element) {
    $(this).find('div').each(function(index, element) {
        total[index]+= parseInt($(this).text())
    });
});

$('.update').find('div').each(function(index, element) {
    $(this).text(total[index])
});

Upvotes: 0

Views: 3100

Answers (2)

Jason P
Jason P

Reputation: 27012

You're trying to add to nothing.

Here's one solution:

total[index] = (total[index] || 0) + parseInt($(this).text())

http://jsfiddle.net/yfC5Z/

Upvotes: 6

DontVoteMeDown
DontVoteMeDown

Reputation: 21465

Try this:

$(this).find('div').each(function(index, element) {
    if (total[index] == undefined) total[index] = 0;
    total[index]+= parseInt($(this).text())
});

Upvotes: 4

Related Questions