views:

39

answers:

2

Here's my HTML Table format :

<table width="580" height="217" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="334">Product</td>
    <td width="246">Price</td>
  </tr>
  <tr>
    <td>Product One</td>
    <td class="price">599</td>
  </tr>
  <tr>
    <td>Product Two</td>
    <td class="price">175</td>
  </tr>
  <tr>
    <td>Product Three</td>
    <td class="price">850</td>
  </tr>
  <tr>
    <td>Product Four</td>
    <td class="price">758</td>
  </tr>
</table>

<p id="grandtotal"></p>

Now, How can i calculate the Grand Total for all the products and display it in paragraph with id "grandtotal"??

Note : The table is dynamically generated, this is just for the demo.

Edited : Added class price for price :), Hope this helps.

+1  A: 

The code as follows works:

var sum = 0;
$('tr:not(:first)').each(function(){
    sum += parseFloat($('td:eq(1)',$(this)).text());
});

$('#grandtotal').html(sum)

However you can make this alot simpler by changing your markup to put the header in a thead node (eliminating the not(:first)) and place a class on your cells indicating the "price" column.

edit: forgot the obligitory jsfiddle -> http://jsfiddle.net/S5Hbe/

Jamiec
Works perfectly with this one.., what if the price is in the forth column?? what to do then????
Roccos
Clearly you change the index in `eq(1)`. However, thats why you should distinguish the price column with its own class if possible.
Jamiec
+2  A: 

Based on your update (and Jamiec solution) you can do :

var sum = 0;
$('.price').each(function() {
    sum += parseFloat($(this).text());
});
$('#grandtotal').html(sum)
Vinze
Great, works perfectly for me
Roccos