我需要编写一个脚本来计算工作时间。我有一个表格,其中包含 6 个可能的小时数,需要将它们添加到底部的字段中。
HTML 看起来像这样:
<table>
<tr>
<td><input type="text" name="amount[]" class="countAmount"></td>
<td>(...)</td>
</tr>
<tr>
<td><input type="text" name="amount[]" class="countAmount"></td>
<td>(...)</td>
</tr>
<tr>
<td><input type="text" name="amount[]" class="countAmount"></td>
<td>(...)</td>
</tr>
<tr>
<td>Total: <span id="total"></span></td>
</tr>
</table>
我正在尝试将 countAmount
类的值一起计数。
我不知道从哪里开始编写 jQuery 代码。我尝试的一切都没有用,但主要问题是如何处理空值以及如何将这些值作为 INT 处理。
最佳答案
查找输入:
var inputs = $('input.countAmount');
要转换为数字并处理空格:
var num = parseInt($(input).val(), 10);
if (!isNaN(num)) {
// It's a valid number, not blank, not "a" or "q", etc.
}
要循环遍历它们,请使用each
。
所以:
var total = 0;
$('input.classAmount').each(function() {
var num = parseInt(this.value, 10);
if (!isNaN(num)) {
total += num;
}
});
...因为在循环中,this
将是输入
,并且要获取输入的值,您不需要 jQuery,即 值
属性很好。
然后将其放入您的total
范围中:
$("#total").text(String(total));
关于jquery - 使用 jQuery 对同一类的输入值进行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13679132/