tags:

views:

38

answers:

1

Hi

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..

Plz help and advice

Greeting

+3  A: 

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);
Philippe Leybaert
Also you might want to use parseInt(___, 10)--specifying base 10--to avoid javascript interpreting as octal base a number that starts with a 0.
Plynx
Agreed. Always specify the radix. Even when you're sure you don't have to.
Christopher Parker
Also... why not save some bytes and use the `+=` operator? `total += parseInt($(this).text(), 10);`
Christopher Parker