I'm just wondering if this is possible, and if not, the best way to set up event handlers to make this happen...
If I have a spreadsheet-like HTML table like so:
<table>
<tr id="row1">
<td><input type="text" class="number" value="1"/></td>
<td><input type="text" class="number" value="2"/></td>
<td><input type="text" class="total" /></td>
</tr>
</table>
can I write a function along the lines of:
function getTotal() {
var total = 0;
$("#row1 .number").each(function() {
total += Number($(this).val());
};
return total;
}
$("#row1 .total").val(getTotal);
So that the value of the input total
automatically changes to the sum of the number
inputs in that row (without having to set onchange
event handlers for each number
input)?
Ideally, I want the value of total to just change because it's set to be the sum of the other inputs, so that it will set itself to the sum both with the page loads and for any changes to the inputs that its value is derived from.
I'm trying to make a page where the user enters values in the non-total cells, and a function will validate the input, and ideally I'd like to avoid having to update every row each time a user makes a change, but at the same time I don't want to make things overly-complicated by having to write out that the total cell should only update when a cell in its row changes.