在另一个 CheckBox 的基础上选中取消选中所有 CheckBox

Suh*_*jua 5 javascript c# asp.net checkbox jquery

当用户单击第一个复选框(All)时,我想选择和取消选择所有复选框。如果用户取消选中任何复选框,则只应取消选中该复选框和第一个复选框(全部),其余复选框不做任何更改。

Checkboxlist我的页面中有一个动态填充的页面。

<asp:CheckBoxList runat="server" ID="cbExtList" />
Run Code Online (Sandbox Code Playgroud)

背后的代码

private Extensions _extension = new Extensions();
private ExtCollection _extCollection = new ExtCollection();

_extCollection = _extension.GetAll();

Dictionary<int, string> dExtensions = new Dictionary<int, string>();

dExtensions.Add(0, "All");
foreach (Extensions ext in _extCollection)
{
    dExtensions.Add(ext.ID, ext.Extension);
}

this.cbExtList.DataSource = dExtensions;
this.cbExtList.DataTextField = "Value";
this.cbExtList.DataValueField = "Key";
this.cbExtList.DataBind();
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

现在一切正常。我只想在单击此中的第一个复选框“全部”时选择所有扩展Checkboxlist

这就是我尝试使用代码隐藏方法的方法。

随着OnSelectedIndexChanged和设置AutoPostBack = True

<asp:CheckBoxList runat="server" ID="cbExtList" OnSelectedIndexChanged="cbExtList_OnSelectedIndexChanged" AutoPostBack="True" />

protected void cbExtList_OnSelectedIndexChanged(object sender, EventArgs e)
{
    try
    {
        if (Convert.ToInt32(this.cbExtList.SelectedItem.Value) == 0)
        {
            foreach (ListItem li in cbExtList.Items)
            {
                li.Selected = true;
            }
        }
        else
        {
            foreach (ListItem li in cbExtList.Items)
            {
                li.Selected = false;
            }
        }
    }
    catch (Exception ex)
    {
        Monitoring.WriteException(ex);
    }
}
Run Code Online (Sandbox Code Playgroud)

Suh*_*jua 2

jQuery 的方式来做到这一点。

这是我实现给定功能所需的唯一 jQuery 代码。

$(document).ready(function() {

    $('[id$=checkAllExts]').click(function () {
        $('input:checkbox').not(this).prop('checked', this.checked);
    });

    $("[id*=cbExtList_]").change(function () {
        if ($('input[id*=cbExtList_][type=checkbox]:checked').length == $('input[id*=cbExtList_][type=checkbox]').length) {
            $('[id$=checkAllExts]').prop('checked', true);
        } else {
            $('[id$=checkAllExts]').prop('checked', false);
        }
    });

});
Run Code Online (Sandbox Code Playgroud)

为了获取 ASP.NET 控件的 ID,我使用了 jQuery 属性选择器,这是一种更好、更简单的直接方法。

[名称$=“值”]

选择具有指定属性且值完全以给定字符串结尾的元素。比较区分大小写。

[名称*=“值”]

选择具有指定属性且其值包含给定子字符串的元素。

因此$('[id$=checkAllExts]'),仅返回我选择/取消选择所有复选框的父复选框。

并向$('[id$=cbExtList_]')我返回除父复选框之外的所有复选框,并相应地执行我的操作。

旧答案

CheckBoxList客户端用JavaScript检查和取消检查的解决方案。

JavaScript 的方式来做到这一点。

<script type="text/javascript">
        var Counter;

        function ExtAll(CheckBox)
        {
            //Get target base & child control.
            var TargetBaseControl = document.getElementById('<%= this.leftCB.ClientID %>');
            var TargetChildControl = "cbExtList";

            //Get all the control of the type INPUT in the base control.
            var Inputs = TargetBaseControl.getElementsByTagName("input");

            //Checked/Unchecked all the checkBoxes.
            for (var n = 0; n < Inputs.length; ++n) {
                if (Inputs[n].type == 'checkbox' && Inputs[n].id.indexOf(TargetChildControl, 0) >= 0)
                    Inputs[n].checked = CheckBox.checked;
                //Reset Counter
            }
            Counter = CheckBox.checked ? TotalChkBx : 0;
        }

        function ChildClick(CheckBox, HCheckBox)
        {
            //get target base & child control.
            var HeaderCheckBox = document.getElementById(HCheckBox);

            //Modifiy Counter;            
            if(CheckBox.checked && Counter < TotalChkBx)
                Counter++;
            else if(Counter > 0) 
                Counter--;

            //Change state of the header CheckBox.
            if(Counter < TotalChkBx)
                HeaderCheckBox.checked = false;
            else if(Counter == TotalChkBx)
                HeaderCheckBox.checked = true;
        }
</script>
Run Code Online (Sandbox Code Playgroud)

我在复选框列表之前添加了一个复选框,以使用其引用来选择/取消选择复选框列表。在该复选框上,我将在事件发生时调用 JavaScript 函数onclick

<div id="leftCB" class="lbl" style="padding-left: 0px;" runat="server">
    <asp:CheckBox runat="server" ID="checkAllExts" Text="All" onclick="javascript:ExtAll(this);" />
    <asp:CheckBoxList runat="server" ID="cbExtList" />
</div>
Run Code Online (Sandbox Code Playgroud)

代码隐藏

private Extensions _extension = new Extensions();
private ExtCollection _extCollection = new ExtCollection();

_extCollection = _extension.GetAll();

Dictionary<int, string> dExtensions = new Dictionary<int, string>();

foreach (Extensions ext in _extCollection)
{
    dExtensions.Add(ext.ID, ext.Extension);

    // Added the below line for the functionality of CheckBoxList
    // which adds an attribute with all of the checkboxes in the CheckBoxList

    this.cbExtList.Attributes["onclick"] = string.Format("javascript:ChildClick(this,'{0}');", this.checkAllExts.ClientID);
}

this.cbExtList.DataSource = dExtensions;
this.cbExtList.DataTextField = "Value";
this.cbExtList.DataValueField = "Key";
this.cbExtList.DataBind();
Run Code Online (Sandbox Code Playgroud)