You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC Razor中如何统计表格内选中的复选框数量

如何仅统计表格内选中的复选框数量?

没问题,这个问题很好解决——你只需要调整jQuery选择器的范围,就能精准统计表格内的目标复选框,排除页面上其他无关的复选框。

先明确你的问题根源:
你当前的脚本使用$('input[type="checkbox"]')会抓取页面上所有复选框,包括表格外的那个独立<input type="checkbox" />,所以统计结果才会包含不该计算的项。

解决方案1:精准限定选择器范围

直接修改选择器,只选中带有table类的表格内部的复选框,替换你的原有脚本即可:

var $checkboxes = $('table.table input[type="checkbox"]');
$checkboxes.change(function () {
  var countCheckedCheckboxes = $checkboxes.filter(':checked').length;
  $('#edit-count-checked-checkboxes').val(countCheckedCheckboxes);
});

解决方案2:事件委托(适合动态表格场景)

如果你的表格是动态渲染的(比如通过异步请求添加新行),上面的绑定方式可能无法作用于新添加的复选框,这时候推荐使用事件委托:

// 监听表格的change事件,仅响应内部的复选框
$('table.table').on('change', 'input[type="checkbox"]', function() {
  // 统计表格内选中的复选框数量
  var countChecked = $('table.table input[type="checkbox"]:checked').length;
  $('#edit-count-checked-checkboxes').val(countChecked);
});

额外优化(可选)

如果想更精准地定位到Selected列下的复选框(避免表格内其他列可能存在的复选框),可以把选择器改成:

$('table.table tr td:first-child input[type="checkbox"]')

这个选择器会只选中表格第一列(也就是你的Selected列)里的复选框,进一步缩小统计范围。


你的原始代码参考

<input type="checkbox" /> 
<table class="table"> 
  <tr> 
    <th> Selected </th> 
    <th> Name </th> 
  </tr> 
  <tr> 
    <td> @Html.CheckBoxFor(modelitem => item.IsChecked, new {}) </td> <!-- 仅统计此复选框 -->
    <td> @Html.DisplayFor(modelitem => item.Name) </td> 
  </tr> 
</table> 
<input type="text" class="form-control" id="edit-count-checked-checkboxes" name="count-checked-checkboxes" readonly="readonly" /> 
<script> 
var $checkboxes = $(' input[type="checkbox"]'); 
$checkboxes.change(function () { 
  var countCheckedCheckboxes = $checkboxes.filter(':checked').length; 
  $('#edit-count-checked-checkboxes').val(countCheckedCheckboxes); 
}); 
</script>

内容的提问来源于stack exchange,提问作者chaeusang chen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 03:43:29