如何选中一个复选框时选择全部
我有一个表格,我填写一些数据,并有每个复选框,最后一个复选框是“全部”。 当我选中此“全部”复选框时,应选中剩余复选框,反之亦然。
填写数据的代码。
Function Add Edit View Delete All @foreach (var item in Model) { @item.FunctionName }
我的UI看起来像 :
试试这个
$('#checkboxAll').on('change', function () { $(this).closest('.grouprow').find(':checkbox').not(this).prop('checked', this.checked); }); $('table tr input:checkbox:not("#checkboxAll")').on('change', function () { if (!this.checked) { $('#checkboxAll').prop('checked', false); } });
DEMO
尝试
jQuery(function ($) { //listen to the change of checkbox in the last td $('.tablecontatiner td:last-child input').on('change', function () { //update the checked property of all checkboxes in the same row as the changed checkbox $(this).closest('tr').find('input[type="checkbox"]').not(this).prop('checked', this.checked); }) })
尝试,
$(’#chkAll’)。on(’click’,function(){$(this).closest(’。grouprow’)。find(’:checkbox’)。not(this).prop(’checked’, this.checked);});
Anton的解决方案非常优雅。 如果您加载(或重新加载)表并且不想在每次重新加载时设置事件处理程序,那么我会改变一点解决方案:
$('.tablecontatiner').on('change', '[id$=All]', function () { $(this).closest('.grouprow').find('input').not(this).prop('checked', this.checked); });
备注 :我也会给每个“ ALL ”复选框提供“checkboxAll”类,所以它看起来像:
然后上面的代码将是:
$('.tablecontatiner').on('change', '.checkboxAll', function () { $(this).closest('.grouprow').find('input').not(this).prop('checked', this.checked); });