Sam Vloeberghs
Sam Vloeberghs

Reputation: 33

iterate through each selector jquery

I'm having problems calculating stuff on my web app. Here is the scenario:

I have a html markup like this:

<table>
   <tr>
       <td><span class="sub_total">10</span></td>
   </tr>
   <tr>
       <td><span class="sub_total">10</span></td>
   </tr>
   <tr>
       <td><span class="sub_total">10</span></td>
   </tr>
</table>

<p><span id="total"></span></p>

I would like to calculate the main total of all the sub totals:

    var total;
    $('.sub_total').each(function(){
        total = total + parseInt($(this).text());
    });

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

But I can't get this to work. I get a NaN notification..

Upvotes: 0

Views: 169

Answers (1)

Philippe Leybaert
Philippe Leybaert

Reputation: 171744

You have to initialize total to 0:

var total = 0; // <-- initialize to zero

$('.sub_total').each(function(){
    total = total + parseInt($(this).text());
});

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

Upvotes: 3

Related Questions