EDIT: I updated my answer to reflect the actual example HTML that Mike provided, which you can view in this fiddle. That link also contains the working javascript from below.
If you have a specific selector for the inputs you want to sum (like a class name), as well as one for the total, you should be able to do this (here's a fiddle link with this javascript in action: http://jsfiddle.net/avidal/zfjmD/):
$('input.sum').change(function() {
var sum = 0;
// we want to sum up the values of all input.sum elements that are in the same tr
// as this one
$(this).closest('tr').find('input.sum').each(function(i) {
var val = parseInt($(this).val(), 10);
/*
change the above line to:
var val = parseFloat($(this).val());
if the inputs will be floats
*/
if (isNaN(val) || val === undefined) {
return;
}
sum += val;
});
$(this).closest('tr').find('input.total').val(sum);
});
The important things to note are the .closest()
function, and the .find()
function.
First, we bind to the change
event for all inputs with a class of sum. When one of those elements is changed (the value changes, then the user clicks/tabs out), we look for the closest
tr
element, then find
the list of inputs with a class of sum that are children of that tr
. For each
of those inputs, we parse the value and accumulate the sum
. After we've iterated over each
of those inputs, we finally find the input with a class of total that's a descendant of the closest tr, and set the val
of that input to the accumulated sum
Perfect!