How do I use jquery to total fields in rows for a variable number of rows
I am trying to add the option fields on a row to the开发者_C百科 total field on the row, using jquery. I can't use ids because there are a variable number of rows, that get created with clone as the user needs them.
<tr>
<td><input name="option_1[]" type="text" class="integer add_to_total" /></td>
<td><input name="option_2[]" type="text" class="numeric add_to_total"/> </td>
<td><input name="option_3[]" type="text" class="numeric add_to_total"/> </td>
<td><input name="total[]" type="text" class="numeric is_total" /> </td>
</tr>
I thought of attaching a change event to the input fields with the 'add_to_total' class and using the sibling function to add to the 'is_total' class. but I can't get that syntax right:
$(".add_to_total").change(function() {
var line_total = 0;
line_total += $(this + " .add_to_total").siblings().val();
$(this + " .is_total").siblings().val(line_total);
});
I get syntax errors and it doesn't work.
$('.add_to_total').change(function(){
var total = 0;
var row = $(this).closest('tr');
row.find('.add_to_total').each(function(){
total += this.value.replace(/[^\d\.-]/,'')*1;
});
row.find('.is_total').val( total );
});
The replace()
allows the user to enter 1,000
and not have you end up with NaN
for your total.
If speed is a big concern, I might suggest caching the row.find('.add_to_total')
as jQuery data on the row, but that's an optimization best left until you're sure you need it.
To do what you've suggested, you'll use something like:
$(".add_to_total").change(function() {
var total = 0;
$(".add_to_total").each(function() {
total += Number($(this).val());
});
$(".is_total").val(total);
});
The trick is that even when just one changes you have to recalculate the sum of all of them.
EDIT: On a per-row basis, this might work:
$("tr > .add_to_total").parent().each(function() {
var tr = $(this);
tr.find(".add_to_total").change(function() {
var total = 0;
tr.find(".add_to_total").each(function() {
total += Number($(this).val());
});
tr.find(".is_total").val(total);
});
});
精彩评论