October Eleven
October Eleven

Reputation: 142

jQuery: Adding up multiple dynamic values

What I'm trying to achieve is this:

I have multiple td's with the same class but different values.

<td class="goals_238"> 3 </td>
<td class="goals_311"> 0 </td>
<td class="goals_128"> 1 </td>
<td class="goals_238"> 4 </td>
<td class="goals_238"> 3 </td>

I want to get the values of "goals_238" and add them up.

The end result for "goals_238" would be = 10

This whole thing is for a sports results table, hence "goals" classes.

I can get to print how many times "goals_238" appears, but doing the math is whole other level for me.

var gamesPlayed = ( $('.goals_238').length );
$('p#goals_238').html(gamesPlayed);

Any clues on how would I go about this?

Upvotes: 1

Views: 142

Answers (1)

PinnyM
PinnyM

Reputation: 35533

var sum = 0;
$.each($('.goals_238'), function(i, e){
    sum += parseInt($(e).html());
});

Upvotes: 3

Related Questions