在子复选框上勾选所有复选框

Check All Checkbox on SubCheckbox

本文关键字:复选框      更新时间:2023-09-26

我在MVC项目上有两个WebGrid列。第一列用于折叠子数据,另一列用于复选框。

此复选框将选中其子数据上的所有复选框。问题是我不能选择子复选框上的所有数据。这是我的示例代码:

//This colum will generate checkbox for the main data
   wbclCol.Add(new WebGridColumn
{
    ColumnName = "",
    Header = "",
    CanSort = false,
    Format = (objChildItem) =>
    {
        StringBuilder strbHtml = new StringBuilder();
        strbHtml.Append("<input class='obj-parmain'  name='lngID' value='" + objChildItem.lngPARID + "' data-pardata='" + objChildItem.lngID+ "' data-show='True' type='checkbox' ></input>");
        return new MvcHtmlString(strbHtml.ToString());
    }
});
//This column will generate another column for the sub-data:
 wbclCol.Add(new WebGridColumn
{
    ColumnName = "",
    Header = "",
    CanSort = false,
    Format = (objChildItem) =>
    {
        StringBuilder strbHtml = new StringBuilder();
        strbHtml.Append("<input class='obj-parsub'  name='lngID' value='" + objChildItem.lngPARID + "' data-pardata='" + objChildItem.lngID+ "' data-show='True' type='checkbox' ></input>");
        return new MvcHtmlString(strbHtml.ToString());
    }
});

这是我的javascript选择所有的复选框类:obj-parsub当我的复选框类:obj-parmain是检查

 function fncParMainCheck() {
        $(document).off('click', '.obj-parmain');
        $(document).on('click', '.obj-parmain', function (e) {
            var blIsCheck = $(this).is(':checked');
            if (blIsCheck) {
                //var objNext = $('.obj-parsub').nextAll();
                //var objNextMain = $(this).siblings().nextAll().find('.obj-parsub');
                //var objNextMain = $(this).closest('.obj-parmain').find('.obj-parsub').prop('checked', this.checked);
                $(this).closest('.obj-parmain').find('.obj-parsub').parent().parent().nextAll().prop('checked', this.checked);
                //$(objNextMain).prop('checked', blIsCheck);
            }
        });
    }

试试下面的代码。首先你要检查你的复选框是否被选中。

$(document).on('change', '.obj-parmain', function (e) {
if ($(this).is(':checked')){
 $('input:checkbox.obj-parsub').prop('checked', $(this).prop('checked'));
}
else{
    // uncheck logic
  }
});

试一下

$(document).on('change', '.obj-parmain', function (e) {
$('.obj-parsub input[type="checkbox"]').prop('checked', $(this).prop('checked'));
});

如果您遇到同样的问题,这个方法非常有效:

 function fncParMainCheck() {
        $(document).off('click', '.obj-parmain');
        $(document).on('click', '.obj-parmain', function () {
            var blIsCheck = $(this).is(':checked');
            if (blIsCheck) {
                //This will look for the sublist of checkbox that is under class name obj-parsub and checks everything
                var objNext = $(this).parent().parent().find('.obj-parsub');
                $(objNext).prop('checked', blIsCheck);
            }
        });
    }