hossein barzegari - 2 years ago 128
HTML Question

How to calculate sum of value in one column of all rows table table finding

I have a table like this :

HTML:

``````<table>
<tr><td>value1</td><td>value2</td><td>value3</td></tr>
....
<tr><td>value1</td><td>value2</td><td>value3</td></tr>
</table>
``````

and wants to calculate sum of each rows on the bottom of table by adding dynamic rows with jquery.

this is sample table before calculate with jQuery.

``````2   3   4
7   1   2
32  58  4
``````

and this is the result :

``````2   3   4
7   1   2
32  58  4
41  62  10
``````

JQuery:

``````\$("tr").each(function(){
var tdCount= \$(this).find("td").length;
for(i=0;i<tdCount;i++)
{
newRow[i]+=parseInt(\$(this).eq(i).value);
}
});
var row="<tr>";
for (i=0;i<newRow.length;i++)
row+="<td>"+newRow[i]+"</td>";
row+="</tr>";
\$("table").append(row);
``````

You can do it like following.

``````\$('table tfoot td').each(function(index) {
var total = 0;
\$('tbody tr').each(function() {
total += +\$('td', this).eq(index).text(); //+ will convert string to number
});
\$(this).text(total);
})``````
``````<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr><td>2</td><td>3</td><td>4</td></tr>
<tr><td>7</td><td>1</td><td>2</td></tr>
<tr><td>32</td><td>58</td><td>4</td></tr>
</tbody>
<tfoot>
<tr><td></td><td></td><td></td></tr>
</tfoot>
</table>``````

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download