我需要对OnKeyup
或OnChange
的列求和
这是我的代码:
$(document).ready(function() {
$(".expenses").on('keyup change', calculateSum);
});
function calculateSum() {
var $input = $(this);
var $row = $input.closest('tr');
var sum = 0;
$row.find(".expenses").each(function() {
sum += parseFloat(this.value) || 0;
});
$row.find(".expenses_sum").val(sum.toFixed(2));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
<tr>
<th>sl</th>
<th>TA</th>
<th>DA</th>
</tr>
<tr>
<td>1</td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
</tr>
<tr>
<td>2</td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
</tr>
<tr>
<td>Total</td>
<td><input class="expenses_sum"></td>
<td><input class="expenses_sum"></td>
</tr>
</table>
答案 0 :(得分:2)
这是输入的“上下文”重要的时刻:您要更新输入元素被更新的相同列中的总和。
您可以做的是:
<td>
元素的索引.filter()
)所有.expenses
元素以确保其父级的<td>
索引与您在步骤2中确定的匹配来完成的。.expenses_sum
元素上设置总和。通过过滤所有.expenses_sum
元素并仅获取其父<td>
索引匹配的元素来完成此操作一些其他提示:
onInput
事件。为了方便起见,对于输入元素,它涵盖onKeyUp
和onChange
事件。<input type="number" />
防止用户错误输入非数字字符<input readonly />
元素上使用.expenses_sum
,以使用户不会自己弄乱这个金额+
运算符(即+this.value
)来完成。请记住,按照规范,所有输入元素,无论其type
,其值始终为string
.each(calculateSum)
绑定到您的原始选择中,以便在首次加载页面时也计算总和,即$(".expenses").on('input', calculateSum).each(calculateSum);
。例如,当.expenses
元素可能已预填充了服务器端的值时(或者如果您手动定义了value="..."
),这将非常有用。请参见下面的概念验证:
$(document).ready(function() {
$(".expenses").on('input', calculateSum).each(calculateSum);
});
function calculateSum() {
// Get the index of the parent `<td>` element
var cellIndex = $(this).closest('td').index();
// Get the values of expenses in the same column as the `<td>` element
var allExpensesInSameColumn = $('.expenses').map(function() {
if ($(this).closest('td').index() !== cellIndex)
return;
return +this.value;
}).get();
// Calculate the sum from returned array of values
var sumOfExpensesInSameColumn = allExpensesInSameColumn.reduce(function(acc, curVal) {
return acc + curVal;
});
// Set the sum on the `.expenses_sum` element in the corresponding column
$('.expenses_sum').each(function() {
if ($(this).closest('td').index() !== cellIndex)
return;
this.value = sumOfExpensesInSameColumn;
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
<tr>
<th>sl</th>
<th>TA</th>
<th>DA</th>
</tr>
<tr>
<td>1</td>
<td><input class="expenses" type="number" /></td>
<td><input class="expenses" type="number" /></td>
</tr>
<tr>
<td>2</td>
<td><input class="expenses" type="number" /></td>
<td><input class="expenses" type="number" /></td>
</tr>
<tr>
<td>Total</td>
<td><input class="expenses_sum" readonly></td>
<td><input class="expenses_sum" readonly></td>
</tr>
</table>