Reputation: 2185
I'm modifying this great post to sum the values of each column in a table. The reason I'm using it is because the table can be unlimited rows and columns.
In this mod, I need to get the values of a text input instead of the cell text. I've change the 2nd line of the sumOfColumns() function to include a find find("input:nth-child(" + columnIndex + ")")
to get all the table row's inputs instead of the children("td:nth-child(" + columnIndex + ")")
. However it is not finding them. I though find() gets all children regardless of depth?
function sumOfColumns(table, columnIndex) {
var tot = 0;
table.find("tr").find("input:nth-child(" + columnIndex + ")")
.each(function() {
$this = $(this);
console.log($this);
if (!$this.hasClass("sum")) {
tot += parseInt($this.value());
}
});
return tot;
}
function do_sums() {
$("tr.sum").each(function(i, tr) {
$tr = $(tr);
//console.log($tr);
$tr.children().each(function(i, td) {
$td = $(td);
//console.log($td);
var table = $td.parent().parent().parent();
if ($td.hasClass("sum")) {
$td.html(sumOfColumns(table, i+1));
}
})
});
}
<table>
<tr>
<th>balance</th>
<td><input type="text" onchange="do_sums();"></td>
</tr>
<tr>
<th>gains</th>
<td><input type="text" onchange="do_sums();"></td>
</tr>
<tr>
<th>loses</th>
<td>-<input type="text" onchange="do_sums();"></td>
</tr>
<tr class="sum">
<th>Total</th>
<td class="sum">#</td>
</tr>
</table>
How can I get the value of each input per column?
Upvotes: 1
Views: 75
Reputation: 7034
The problem is you're looking for an input
which is the nth child, but the input
isn't the nth child of it's parent (the td).
What you really want to find is an input
that's inside a td
that's the nth child.
find("td:nth-child(" + columnIndex + ") input")
Upvotes: 1