Dynamically adding the sum of field in Jquery

旧城冷巷雨未停 提交于 2019-12-12 03:34:48

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!