JQUERY: Apply same function on multiple Input fields
I have a form on which user is adding text fields as many as they require, all text fields have the same CSS class "amount". I have a JQUERY function to sum up values in this fields and refresh sum when user changes value in any of these fields. The problem is that it triggers only when user changes values in first field. How to apply it on every field he adds to form?
HTML:
<input type="text" name="amount[]" class=".amount" />
JS:
function sumItUp() {
var sum = 0;
//iterate through each textboxes and add the values
$(".amount").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {开发者_JS百科
sum += parseFloat(this.value);
}
});
$("#sumFin").html(sum.toFixed(2));
}
$('.amount').change(function() {
sumItUp();
});
How to make this last part trigger on each .amount change?
Thanks.
$('.amount').live("change", function() { sumItUp(); });
.live() will apply events to things currently in the DOM and added later
You need to use live()
which keeps track of new matched elements and attaches the handler to them
$('.amount').live("change", function() {
sumItUp();
});
精彩评论