Check/Uncheck all Items in an ASP.NET CheckBox List using jQuery

Posted by: Suprotim Agarwal , on 11/28/2008, in Category jQuery and ASP.NET
Views: 167569
Abstract: In this article, we will explore how to use jQuery to select unselect all the checkboxes in an ASP.NET CheckBoxList.
Check/Uncheck all Items in an ASP.NET CheckBox List using jQuery
 
The CheckBoxList control in ASP.NET provides a group of checkboxes that can be dynamically generated by binding it to a data source. A few months ago, I had written a similar article using ASP.NET and JavaScript over here Check/Uncheck all items in a CheckBoxList using ASP.NET and Javascript . The approach we had taken using JavaScript was, we first retrieved the checkboxlist control using document.getElementById(cbControl) and then counted the number of <input> tags inside that control. Once we got the count, we used a loop to set the state of each control.  
In this article, we will explore how to use jQuery to select  unselect all the checkboxes in an ASP.NET CheckBoxList. If you are new to jQuery, check this: Using jQuery with ASP.NET - A Beginner's Guide
Open Visual Studio 2008 > File > New > Website > Choose ‘ASP.NET 3.5 website’ from the templates > Choose your language (C# or VB) > Enter the location > Ok. In the Solution Explorer, right click your project > New Folder > rename the folder as ‘Scripts’.
Right click the Scripts folder > Add Existing Item > Browse to the path where you downloaded the jQuery library (jquery-1.2.6.js) and the intellisense documentation (jquery-1.2.6-vsdoc.js) > Select the files and click Add.
Now drag and drop the jquery-1.2.6.js file from the Solution Explorer on to your page to create a reference as shown below
jQuery Ref
Drag and drop a CheckBoxList control to the page. Rename it to ‘cbList’.
<asp:CheckBoxList ID="cbList" runat="server">
</asp:CheckBoxList>
Now add items programmatically to the CheckBoxList by using the following code at the Page load event:
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        cbList.Items.Add(new ListItem("Items 1", "Items 1"));
        cbList.Items.Add(new ListItem("Items 2", "Items 2"));
        cbList.Items.Add(new ListItem("Items 3", "Items 3"));
        cbList.Items.Add(new ListItem("Items 4", "Items 4"));
        cbList.Items.Add(new ListItem("Items 5", "Items 5"));
    }
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
      If (Not Page.IsPostBack) Then
            cbList.Items.Add(New ListItem("Items 1", "Items 1"))
            cbList.Items.Add(New ListItem("Items 2", "Items 2"))
            cbList.Items.Add(New ListItem("Items 3", "Items 3"))
            cbList.Items.Add(New ListItem("Items 4", "Items 4"))
            cbList.Items.Add(New ListItem("Items 5", "Items 5"))
      End If
End Sub
Now drag and drop a CheckBox from the toolbox to the page and rename it as ‘chkAll’. Now if you observe the JavaScript solution in a previous article over here, I had to loop through the checkboxes and then set its ‘checked’ property. Let us see how we can achieve this in jQuery using 3 different jQuery approaches.
I have included all these approaches to show you how I reduced my code from Approach 1 to Approach 3
Approach 1: The longer approach
           $("#chkAll").toggle(
                function() {
                    $("input[@type='checkbox']").not('#chkAll').each(function() {
                        this.checked = true;
                            });
                   },
                function() {
                    $("input[@type='checkbox']").not('#chkAll').each(function() {
                      this.checked = false;
                });
                });
            });
Approach 2: Shortening the approach
   <script type="text/javascript">
        $(document).ready(function() {
           $("#chkAll").toggle(
            function() {
            $('input[@type=checkbox]').attr('checked', 'true');
            },
            function() {
            $('input[@type=checkbox]').removeAttr('checked');           
            });         
        });
 
    </script>
Approach 3: Freezing it
    <script type="text/javascript">
        $(document).ready(function() {
            $('#chkAll').click(
             function() {
                 $("INPUT[type='checkbox']").attr('checked', $('#chkAll').is(':checked'));
             });
         });
 
I liked the last approach which I got from here. In the code above, we are first assigning the click event to the CheckBox(chkAll).
<script type="text/javascript">
        $(document).ready(function() {
            $('#chkAll').click(
 
When the user clicks the checkbox, we run a function which finds all elements of the checkbox type and sets the ‘checked’ value of all items in the CheckBoxList to true or false based on the checked value of the ‘chkAll’ checkbox.
If you have multiple checkboxlist on your page, you can pass the CheckBoxList name and id as a parameter to the jQuery function as shown here:
 $("INPUT[@name=" + name + "][type='checkbox']").attr('checked', $('#' + id).is(':checked'));
The entire code with the finalized approach (Approach 3) will look similar to the following:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Check/Uncheck All CheckBoxes Using JQuery</title>
 
    <script src="Scripts/jquery-1.2.6.js" type="text/javascript"></script>
   
    <script type="text/javascript">
        $(document).ready(function() {
            $('#chkAll').click(
             function() {
                 $("INPUT[type='checkbox']").attr('checked', $('#chkAll').is(':checked'));
             });
         });    
        
     </script>
   
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <asp:CheckBox ID="chkAll" runat="server" Text="Check All" /><br />
   
        <asp:CheckBoxList ID="cbList" runat="server">
        </asp:CheckBoxList>
       
    </div>
    </form>
</body>
</html>
 
On running the application, you get a screen similar to the following:
jQuery
On clicking the CheckAll checkbox, all the checkboxes gets selected, similar to a gmail application
Check All
On clicking the CheckAll checkbox again, the checkboxes gets unselected.
Uncheck All
I hope you liked the article and I thank you for viewing it.
If you liked the article,  Subscribe to my RSS Feed or Subscribe Via Email
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, DNC .NET Magazine, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls. and is authoring another one at The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by heaiping on Thursday, December 4, 2008 9:34 AM
thanks a lot !
Comment posted by Gilbert on Thursday, December 4, 2008 10:08 AM
awesome site with lots of content!
Comment posted by Killer on Thursday, December 4, 2008 6:46 PM
Confusing. Approach 1 & 2 seem silly to even state. Anyone who has written this same code in Forms/WPF knows to use approach 3.

Author does not display how to do: "you can pass the CheckBoxList name and id as a parameter to the jQuery function" Who passes the parameters? Is this a hidden jQuery f() sig? or does jQuery auto-assign params based on name->tag-attribute?? Unsure. Author doesn't explain.
Comment posted by Nasif on Wednesday, December 10, 2008 12:55 AM
thanks a lot .. very nice post!!
Comment posted by Tim Hobbs on Friday, December 12, 2008 12:01 PM
@Killer-

You missed the first part of the sentence, "If you have multiple checkbox lists...". The example does not, so the author doesn't explain it. IF you did, then YOU could pass the information (it does say YOU in the sentence). :)

I just implemented this using the same code (must have found the same blog post) but you did miss one thing that I had to add: what if you uncheck a list item's checkbox? The "check all" box stays checked. Add a "click" listener to each checkbox in the list that unchecks the "check all" box if unchecked and you have the perfect solution!

Here is sample code:
$("#cbList INPUT[type='checkbox']").click(
    function(e){
        if (!$(this)[0].checked) {
            $("#chkAll").attr("checked", false);
        }
    }
);
Comment posted by Suprotim Agarwal on Friday, December 12, 2008 12:25 PM
Tim: Thanks for the uncheck code! It's neat!
Comment posted by Indu on Monday, January 19, 2009 3:12 AM
Hello This is very nice detail by you. Thanks for sharing knowledge.
Thanks
Indu
<a href="http://www.nextmvp.blogspot.com/">http://www.nextmvp.blogspot.com/</a>
<a href="http://www.shaktibanna.blogspot.com/">http://www.shaktibanna.blogspot.com/</a>
Comment posted by sangam uprety on Thursday, March 12, 2009 1:28 AM
Simple yet powerful implementation of jquery! Thanks for the great article!!
Comment posted by Gaurav on Tuesday, May 26, 2009 4:23 AM
Good post.. but i have not been able to implement it for two different check list boxes. can u please help me out on that one?
Comment posted by fgfdg on Monday, June 22, 2009 8:18 AM
hi
Comment posted by samy on Thursday, October 8, 2009 3:12 PM
Nice article. Thanks.
Approach 1 and 2 has: "input[@type='checkbox']" which throws an exception.
Seems it should be: "input[type='checkbox']" ---> '@' removed from '@type'
Comment posted by Ali on Thursday, April 14, 2011 2:20 AM
when compile asp.net page, checkbox id`s is changed!!!
help me!
Comment posted by simanta on Tuesday, January 24, 2012 2:28 AM
Hi Sir,

I am simanta . I am new to .net. I am trying to use ajax toggle button extender in check box list . But error is coming.

Thanks in advance

Comment posted by Ravi on Tuesday, March 12, 2013 4:20 AM
  if (CheckBox1.Checked == true)
        {
            foreach (ListItem checkboxitems in CheckBoxList1.Items)
            {
                checkboxitems.Selected = true;
            }
        }
        else if (CheckBox1.Checked == false)
        {
            foreach (ListItem listItem in CheckBoxList1.Items)
            {
                listItem.Selected = false;
            }
        }
Comment posted by RaviRavula on Tuesday, March 12, 2013 4:20 AM
  if (CheckBox1.Checked == true)
        {
            foreach (ListItem checkboxitems in CheckBoxList1.Items)
            {
                checkboxitems.Selected = true;
            }
        }
        else if (CheckBox1.Checked == false)
        {
            foreach (ListItem listItem in CheckBoxList1.Items)
            {
                listItem.Selected = false;
            }
        }
Comment posted by lalit raghuvanshi on Tuesday, June 18, 2013 12:46 AM
really useful article on check/uncheck checkbox list in asp.net.I have also similar article on How to Send email to multiple users based on CheckBox selection inside GridView in asp.net C#,VB.Net ..Please check the link http://www.webcodeexpert.com/2013/06/send-email-to-multiple-users-based-on.html
Comment posted by Indrajeet on Friday, December 6, 2013 4:36 AM
Nice article. Thanks!
Comment posted by santosh menon on Saturday, December 21, 2013 4:07 AM
drag and drop in checklistbox in asp.net from one checklistbox to other
Comment posted by prasad on Wednesday, August 20, 2014 6:23 AM
Dear all,after checking checkbox inside gridview after i need to clear all the checkboxes inside grgidview on page load automatically how is it possible?
Comment posted by deepu on Friday, August 22, 2014 6:53 AM
http://asp-net-by-parijat.blogspot.in/2014/08/check-uncheck-all-aspnet-checkbox-in.html
Check Uncheck all asp.net CheckBox in asp.net using jQuery
CHECK UNCHECK ALL ASP.NET CHECKBOX IN ASP.NET USING JQUERY WITH C# CODE EXAMPLE
Comment posted by jim on Friday, October 17, 2014 1:31 PM
this is good post.  good man keep on posting

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel