Skip to content Skip to sidebar Skip to footer

Check Uncheck All CheckBoxes On The Basis Of Another CheckBox

I want to select and unselect all checkboxes when user clicks on the first checkbox (All). And if user unchecks any checkbox, then only that checkbox and the first checkbox (All) s

Solution 1:

jQuery way to do it.

This is the only jQuery code that I need to achieve the given functionality.

$(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);
        }
    });

});

To get IDs of the ASP.NET controls, I used the jQuery attribute selectors which is a better and simple straight way.

[name$="value"]

Selects elements that have the specified attribute with a value ending exactly with a given string. The comparison is case sensitive.

[name*="value"]

Selects elements that have the specified attribute with a value containing a given substring.

So $('[id$=checkAllExts]') returns me the parent checkbox only on which I select/deselect all checkboxes.

And $('[id$=cbExtList_]') returns me all the checkbox except the parent checkbox and I perform my actions accordingly.

Old Answer

The Solution of checking and unchecking CheckBoxList with JavaScript on client side.

JavaScript way to do it.

<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>

I added a checkbox before my checkboxlist to use its reference to select/unselect the checkboxlist. On that checkbox I'm calling the JavaScript function when onclick event happens.

<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>

Code Behind

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();

Solution 2:

If you need to check all checkboxes on checking of an "all" checkbox and uncheck them all upon unchecking of it, but also needed to disable each checkbox (aside from the "all") checkbox when the "all" checkbox was checked, this code should work for you. It has the added benefit of not requiring JavaScript/jQuery, too.

Here's the .aspx code (for this scenario I have nine facilities that can be selected in any combination):

<asp:Label ID="lblFacility" AssociatedControlID="chkFacility" runat="server" Text="Facility: "></asp:Label>
<asp:CheckBoxList ID="chkFacility" runat="server" OnSelectedIndexChanged="chkFacility_SelectedIndexChanged">
    <asp:ListItem Value="All" Text="All"></asp:ListItem>
    <asp:ListItem Value="Location1" Text="Location 1"></asp:ListItem>
    <asp:ListItem Value="Location2" Text="Location 2"></asp:ListItem>
    <asp:ListItem Value="Location3" Text="Location 3"></asp:ListItem>
    <asp:ListItem Value="Location4" Text="Location 4"></asp:ListItem>
    <asp:ListItem Value="Location5" Text="Location 5"></asp:ListItem>
    <asp:ListItem Value="Location6" Text="Location 6"></asp:ListItem>
    <asp:ListItem Value="Location7" Text="Location 7"></asp:ListItem>
    <asp:ListItem Value="Location8" Text="Location 8"></asp:ListItem>
    <asp:ListItem Value="Location9" Text="Location 9"></asp:ListItem>
</asp:CheckBoxList>

And the Code Behind:

protected void chkFacility_SelectedIndexChanged(object sender, EventArgs e) {
    //disables all the checkboxes when "All" is selected
    if (chkFacility.SelectedIndex==0) {
        foreach(ListItem aListItem in chkFacility.Items) {
            aListItem.Selected = true;
            if (aListItem.Value != "All") {
                aListItem.Enabled = false;
            }
        }
    } else if (chkFacility.SelectedIndex > 0) {
        var i = 0;
        foreach(ListItem aListItem in chkFacility.Items) {
            if (aListItem.Selected) {
                i++;
            }
        }
        //with the i++ check above, this handles unchecking every checkbox when each location is selected and the "All" checkbox is unchecked
        if (i == 9) {
            foreach(ListItem aListItem in chkFacility.Items) {
                aListItem.Selected = false;
                aListItem.Enabled = true;
            }
        //disables the "All" checkbox in all other cases where 8 or fewer of the 9 locations are selected
        } else {
            foreach(ListItem aListItem in chkFacility.Items) {
                if (aListItem.Value == "All") {
                    aListItem.Enabled = false;
                }
            }
        }
    //if no locations are selected after PostBack, make sure all checkboxes are enabled
    } else if (chkFacility.SelectedIndex == -1) {
        foreach(ListItem aListItem in chkFacility.Items) {
            aListItem.Enabled = true;
        }
    }
}

One caveat to this implementation, though, is that the code for whether all locations are selected will also clear out the selection if they're all currently selected by manually checking each one. When I was writing the code for work, this edge case was an acceptable risk considering it was unlikely and considering that if all locations need to be selected, the user should be checking the "All" checkbox instead, anyway.


Solution 3:

I have put together an example using jQuery and Javascript to check/uncheck items in a checkboxlist based on the checked state of the first or All check box.

ASPX:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.23/jquery-ui.min.js" type="text/javascript"></script>

    <script type="text/javascript">
        var checkedState = false;

        function checkAll() {

            $("input[id^=cblMultiple]").each(function () {
                if ($(this).val() == 0) {
                    checkedState = $(this).is(":checked")
                }
                else {
                    $(this).attr("checked", checkedState)
                }
                //console.log(checkedState);
                //console.log($(this).val());
            });
        }

        $(document).ready(function () {
            $("input[id^=cblMultiple]").each(function () {
                if ($(this).val() == 0) {
                    $(this).on("click", checkAll);
                }
            });
        });

    </script>
</head>
<body>

    <form id="form1" runat="server">
        <asp:CheckBoxList runat="server" ID="cblMultiple"/>
    </form>
</body>
</html>

Code Behind

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        cblMultiple.Items.Add(new ListItem("All", "0"));
        for (int i = 1; i < 11; i++)
        {
            cblMultiple.Items.Add(new ListItem("All" + i, i.ToString()));
        }    
    }
}

Solution 4:

loop through the list and set the Selected value of the items to true/false:

for (int i = 0; i < cbExtList.Items.Count; i++)
        {
            cbExtList.Items[i].Selected = true;
        }

Post a Comment for "Check Uncheck All CheckBoxes On The Basis Of Another CheckBox"