I'm looking for the best way to trigger (call) a function which will sum a开发者_StackOverflowll the input fields in all table rows. The problem is, that the field can be manipulated manually (by typing) or with a function - value written to them (which does not trigger an event).
I would like that the sum function would trigger on add/remove row (tr), keypress, focusout...
Btw: i'm cloning the table rows, so they are created dynamically.
Thanks!
$(".val_field:input").live("focusout", function(){
val = parseFloat( $(this).val() );
sum += isNaN(val) ? 0 : val;
$("#sum").val( sum );
});
This question is old but any answer can be useful
function recount(el){
var sum = 0;
el.parents('table').find('.val_field:input').each(function(){
var val = parseFloat( $(this).val() );
sum += isNaN(val) ? 0 : val;
});
$("#sum").val( sum );
}
$('table').on('keypress blur', '.val_field:input', function(){
recount($(this));
});
Of course, you can apply recount()
on row removal too (that's why I factorized it).
精彩评论