Can somebody help me out to troubleshoot this code? I am looking to add all the values of a HTML table column using JQuery. Please see below example I can not get this functional.
The first table is just a normal table holding the data, the second table should be filled dynamically with jQuery adding up the columns.
<html>
<head>
<script type="text/javascript" SRC="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js"></script>
<script type="text/javascript">
//these will hold the totals
var ages = 0;
var weights = 0;
var benchpresses = 0;
//reference the rows you want to add
//this will not include the header row
var rows = $("#data tr:gt(0)");
rows.children("td:nth-child(2)").each(function() {
//each time we add the cell to the total
ages += parseInt($(this).html());
});
rows.children("td:nth-child(3)").each(function() {
weights += parseInt($(this).html());
});
rows.children("td:nth-child(4)").each(function() {
benchpresses += parseInt($(this).html());
});
//then output them to the elements
$("#ages").html(ages);
$("#weights").html(weights);
$("#benchpresses").html(benchpresses);
</script>
</head>
<TABLE class=custom id=data>
<TBODY>
<TR>
<TH>name</TH>
<TH>age</TH>
<TH>weight</TH>
<TH>benchpress</TH>
</TR>
<TR>
<TD>stan</TD>
<TD>27</TD>
<TD>177</TD>
<TD>325</TD>
</TR>
<TR>
<TD>rj</TD>
<TD>30</TD>
<TD>135</TD>
<TD>95</TD>
</TR>
<TR>
<TD>jose</TD>
<TD>29</TD>
<TD>230</TD>
<TD>375</TD>
</TR>
</TBODY>
</TABLE>
<BR>
<TABLE class=custom>
<TBODY>
<TR>
<TH>ages</TH>
<TH>weights</TH>
<TH>benchpresses</TH>
</TR>
<TR>
<TD id=ages> </TD>
<TD id=weights> </TD>
<TD id=benchpresses> </TD>
</TR>
</TBODY>
</TABLE>
</html>
In your example the code to sum the columns will execute before the columns/tables/data exist. Several ways to fix, easiest is to move the
<script>block in your example to after the table definition.