how to find sum of 2 columns in html table using jquery

Posted by Klbaiju under jQuery on 11/18/2016 | Points: 10 | Views : 367 | Status : [Member] | Replies : 1
Hi following is my html table

<table id="grdtable">
<tr><td>Charge</td><td>start</td><td>End</td><td>No</td><td>Total</td></tr>
<tr><td>7</td><td>100</td><td>200</td><td>100</td><td>700</td></tr>
<tr><td>8</td><td>10</td><td>100</td><td>90</td><td>720</td></tr>
<tr><td>9</td><td>20</td><td>50</td><td>30</td><td>270</td></tr>
</table>


its output is as follows

Charge start End No Total
7 100 200 100 700
8 10 100 90 720
9 20 50 30 270

my requiremt is on the click event of button i want add the the result in a variable using each function
var str="";

just like

str= 7 * 100=700
8*90=720
9*30=270

means multiplying first column with fourth column

how to do this

Regards

Baiju




Responses

Posted by: Manicse on: 11/18/2016 [Member] Bronze | Points: 25

Up
0
Down
Hi,

We need to understand the Nodes that which are going to add up like First, Last,Last Child or First child something like.
Once you understand the basic logic in which we are going to perform he operation we can do with the following code as an example.


$("#sum_table tr:last td:not(:first)").text(function(i){

var t = 0;
$(this).parent().prevAll().find("td:nth-child("+(i+2)+")").each(function(){
t += parseInt( $(this).text(), 10 ) || 0;
});
return "Total: " + t;
});



In the above example I have taken last values for adding. So based on your requirement you should change the logic.

Mani.R

Klbaiju, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response