开发者

How to calculate grand total from table cells using jquery

开发者 https://www.devze.com 2023-01-11 18:01 出处:网络
Here\'s my HTML Table format : <table width=\"580\" height=\"217\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">

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>
  </t开发者_运维问答r>
  <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.


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

var sum = 0;
$('.price').each(function() {
    sum += parseFloat($(this).text());
});
$('#grandtotal').html(sum)


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/

0

精彩评论

暂无评论...
验证码 换一张
取 消