Raptor
Raptor

Reputation: 54252

Calculate Grand Total from sub-total

I have a table of sub-totals.

<table>
 <tr>
  <td><span id="subtotal_1">100</span></td>
 </tr>
 <tr>
  <td><span id="subtotal_2">150</span></td>
 </tr>
</table>

Here is my Javascript code to calculate grand total :

var grandtotal = 0;
$('span[id^=subtotal_]').each(function() {
    grandtotal += parseInt($(this).val());
});

but the grandtotal returns nothing. What did I miss?

Upvotes: 0

Views: 199

Answers (2)

Zamboney
Zamboney

Reputation: 2010

just change the .val() to .text()

var grandtotal = 0;
$('span[id^=subtotal_]').each(function() {
    grandtotal += parseInt($(this).text());
});

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388406

You need to use .text() here, .val() is for input fields

var grandtotal = 0;
$('span[id^=subtotal_]').each(function() {
    grandtotal += parseInt($.trim($(this).text()));
});

Demo: Fiddle

Upvotes: 1

Related Questions