问题
I'd like to add the sum of hours in a week using jquery from a table, when text fields change the total in div total_amount should be updated, but it doesn't seem to be working.
$(function() {
$("[id$=day]").change(function() {
var total = 0;
$('table input[id$=day]').each(function() {
var sum_id = this.id;
total[this.value] += parseInt($('#' + sum_id).val(), 10);
});
$('div.total_amount').html(total);
});
});
And the html is here
<td class="timesheet2"><input type="text" name="daymon" id="monday">
</td>
<td class="timesheet2"><input type="text" name="daytue" id="tuesday">
</td>
<td class="timesheet2"><input type="text" name="daywed" id="wednesday">
</td>
<td class="timesheet2"><input type="text" name="daythurs" id="thursday">
</td>
<td class="timesheet2"><input type="text" name="dayfri" id="friday">
</td>
<td class="timesheet2"><input type="text" name="daysat" id="saturday">
</td>
<td class="timesheet2"><input type="text" name="daysun" id="sunday">
</td>
<td class="timesheet"><div id="total_amount"></div>
</td>
回答1:
You had a problem showing the final value. You were using a class selector when you needed an ID.
http://jsfiddle.net/YE5vF/2/
HTML
<table>
<tr>
<td class="timesheet2"><input type="text" name="daymon" id="monday"></td>
<td class="timesheet2"><input type="text" name="daytue" id="tuesday"></td>
<td class="timesheet2"><input type="text" name="daywed" id="wednesday"></td>
<td class="timesheet2"><input type="text" name="daythurs" id="thursday"></td>
<td class="timesheet2"><input type="text" name="dayfri" id="friday"></td>
<td class="timesheet2"><input type="text" name="daysat" id="saturday"></td>
<td class="timesheet2"><input type="text" name="daysun" id="sunday"></td>
<td class="timesheet"><div id="total_amount"></div></td>
</tr>
</table>
JS
$("[id$=day]").change(function() {
var total = 0;
$('.timesheet2 input').each(function() {
total = total + Number( $(this).val() );
});
$('div#total_amount').html(total);
});
回答2:
This could be better I think.
var sum = 0;
$('.timesheet2').each(function() {
sum += Number($(this).val());
});
$('#total_amount').html(sum);
});
来源:https://stackoverflow.com/questions/15363457/dynamically-adding-the-sum-of-field-in-jquery