如何计算复选框的值



我有一个包含以下数据结构的表:

类别类型收入>TA12000重复数据>
ID payroll_cat_name payroll_cat_code金额
1 公积金
2 基本工资 BC35000
3 旅行收入6500
4 家庭津贴 HM 收入
5 税收 TX500

试试这个

<body>
<table>
<tbody>
<tr>
<td><div><input type="checkbox"></div></td>
<td>...</td>
<td>...</td>
<td>deducing</td>
<td>1000</td>
</tr>
<tr>
<td><div><input type="checkbox"></div></td>
<td>...</td>
<td>...</td>
<td>earning</td>
<td>6000</td>
</tr>
<tr>
<td><div><input type="checkbox"></div></td>
<td>...</td>
<td>...</td>
<td>earning</td>
<td>3000</td>
</tr>
<tr>
<td><div><input type="checkbox"></div></td>
<td>...</td>
<td>...</td>
<td>earning</td>
<td>1200</td>
</tr>
<tr>
<td><div><input type="checkbox"></div></td>
<td>...</td>
<td>...</td>
<td>deducing</td>
<td>1000</td>
</tr>
</tbody>
</table>
<button type="button" id="button">Yo</button>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(function() {
$("#button").click(function() {
let total = 0;
$("tbody:first tr").each(function() {
if ($(this).children("td").first().children("div").children("input").is(":checked")) {
if ("deducing" == $(this).children("td").eq(3).text()) total = total - parseInt($(this).children("td").eq(4).text());
else if ("earning" == $(this).children("td").eq(3).text()) total = total + parseInt($(this).children("td").eq(4).text());
}
});
alert(total);
});
});
</script>
</body>

如果我的评论是正确的,这里的问题是你有正确的金额,但已经失去了"元信息";关于是对总数进行加法还是减法,那么我认为最简单的解决方案是执行以下操作:

首先更改复选框的值,使其反映要采取的操作,即如果它是deduction,则将该值设为负值。所以你的input应该是:

<input type='checkbox' name='payroll_group' value=" . ($row['category_type'] === 'deduction' ? $row["amount"] * -1 : $row["amount"]) . "class='form-check-input'>

其中($row['category_type'] === 'deduction' ? $row["amount"] * -1 : $row["amount"])将检查category_type是否为deduction,然后将amount乘以-1,否则保持当前的amount值。请注意,括号是必要的。

然后,在当前的js中,您应该在当前的示例中使用[-1000,35000,6500]。然后你可以做一个简单的循环来遍历数组并添加到总数中,或者你可以使用类似reduce()的东西

var totalAmount = favorite.reduce(
function (total, amount) {
return parseInt(total) + parseInt(amount)
},
0 // The initial value to start with
)

最新更新