Ryan
Ryan

Reputation: 15250

How can I get the sum of all table rows with a certain class in jQuery?

How can I sum the values of only table rows with the countMe class in jQuery?

HTML:

<div id="sum">$0</div>
<table>
    <tr>
        <th>id</th> <th>value</th>
    </tr>
    <tr class="countMe">
        <td>1</td> <td class="v">$10</td>
    </tr>
    <tr>
        <td>2</td> <td class="v">$20</td>
    </tr>
    <tr class="countMe">
        <td>3</td> <td class="v">$10</td>
    </tr>
    <tr>
        <td>4</td> <td class="v">$30</td>
    </tr>
</table>

I need the #sum to say $20. How can I do that?

Upvotes: 0

Views: 844

Answers (2)

Tamil Selvan C
Tamil Selvan C

Reputation: 20199

Try

$(function() {
 var countme = $('.countMe .v'), total=0;
    countme.each(function(key,val) {
        total += parseFloat($(this).text().slice(1));
    });
    $('#sum').html('$'+total);
});

Upvotes: 1

Blender
Blender

Reputation: 298056

You can do something like this:

var sum = 0;

$('tr.countMe td.v').each(function() {
    sum += parseFloat($(this).text().slice(1));
});

$('#sum').text(sum);

Upvotes: 6

Related Questions