Click here to Skip to main content
Click here to Skip to main content

Check all checkboxes in GridView using jQuery

, 2 Aug 2013
Rate this:
Please Sign up or sign in to vote.
Check all checkboxes in GridView using jQuery.

Introduction

This is the very basic need when you do bulk operations like email sending, export to excel, delete record etc. from a list. A CheckBox in header on which checked or unchecked all the CheckBoxes in the list should change respectively. Similar thing you can see in Gmail, Hotmail etc. which have more variations to select record.

In this tutorial I put a CheckBox in header, on its check change, all the checkboxes in the list check change and if you change the check on any of checkboxes in the list the header check also change automatically.

Using the code 

I have created a Class Employee, add some records to it and bind it to grid. 

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string Designation { get; set; }
}

protected void Page_Load(object sender, EventArgs e)
{
    var employees = new List<Employee>()
    {
        new Employee(){ Id = 1, Name = "Ms. Nancy Davolio",     Address = "507 - 20th Ave. E.  Apt. 2A",    Designation = "Sales Representative"},
        new Employee(){ Id = 2, Name = "Dr. Andrew Fuller",     Address = "908 W. Capital Way",             Designation = "Vice President Sales"},
        new Employee(){ Id = 3, Name = "Ms. Janet Leverling",   Address = "722 Moss Bay Blvd.",             Designation = "Sales Representative"},
        new Employee(){ Id = 4,	Name = "Mrs. Margaret Peacock", Address = "4110 Old Redmond Rd.",           Designation = "Sales Representative"},
        new Employee(){ Id = 5,	Name = "Mr. Steven Buchanan",   Address = "14 Garrett Hill",                Designation = "Sales Manager"},
        new Employee(){ Id = 6,	Name = "Mr. Michael Suyama",    Address = "Coventry House  Miner Rd.",      Designation = "Sales Representative"},
        new Employee(){ Id = 7,	Name = "Mr. Robert King",       Address = "Edgeham Hollow  Winchester Way", Designation = "Sales Representative"},
        new Employee(){ Id = 8,	Name = "Ms. Laura Callahan",    Address = "4726 - 11th Ave. N.E.",          Designation = "Inside Sales Coordinator"},
        new Employee(){ Id = 9, Name = "Ms. Anne Dodsworth",    Address = "7 Houndstooth Rd.",              Designation = "Sales Representative"}
    };

    gvEmployees.DataSource = employees;
    gvEmployees.DataBind();
}
  

This is my Grid Control 

<asp:GridView ID="gvEmployees" runat="server" AutoGenerateColumns="false" CellPadding="4" ForeColor="#333333"
    GridLines="None">
    <AlternatingRowStyle BackColor="White" />
    <Columns>
        <asp:TemplateField>
            <HeaderTemplate>
                <asp:CheckBox runat="server" ID="chkAll" />
            </HeaderTemplate>
            <ItemTemplate>
                <asp:CheckBox runat="server" ID="chkEmployee" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="ID">
            <ItemTemplate>
                <asp:Label runat="server" ID="lblID" Text='<%#Eval("Id") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Name">
            <ItemTemplate>
                <asp:Label runat="server" ID="lblName" Text='<%#Eval("Name") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Address">
            <ItemTemplate>
                <asp:Label runat="server" ID="lblAddress" Text='<%#Eval("Address") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Designation">
            <ItemTemplate>
                <asp:Label runat="server" ID="lblDesignation" Text='<%#Eval("Designation") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
    <EditRowStyle BackColor="#7C6F57" />
    <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
    <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
    <RowStyle BackColor="#E3EAEB" />
    <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
    <SortedAscendingCellStyle BackColor="#F8FAFA" />
    <SortedAscendingHeaderStyle BackColor="#246B61" />
    <SortedDescendingCellStyle BackColor="#D4DFE1" />
    <SortedDescendingHeaderStyle BackColor="#15524A" />
</asp:GridView> 

We have two requirements.

1. When top CheckBox checked/unchecked, we have to check/uncheck all the CheckBoxes in the list.

Following function fulfill the requirement. 

$("#<%=gvEmployees.ClientID%> input[id*='chkAll']:checkbox").click(function () {
    //Check/uncheck all checkboxes in list according to main checkbox 
    $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox").attr('checked', $(this).is(':checked'));
});


2. On each of the list CheckBox checked/unchecked, we have to determine Check/Uncheck top CheckBox.     

$("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox").click(function() {
    //Get number of checkboxes in list either checked or not checked
    var totalCheckboxes = $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox").size();
    //Get number of checked checkboxes in list
    var checkedCheckboxes = $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox:checked").size();
    //Check / Uncheck top checkbox if all the checked boxes in list are checked
    $("#<%=gvEmployees.ClientID%> input[id*='chkAll']:checkbox").attr('checked', totalCheckboxes == checkedCheckboxes);
});    

Following is Complete Javascript. 

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox").click(function() {
            //Get number of checkboxes in list either checked or not checked
            var totalCheckboxes = $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox").size();
            //Get number of checked checkboxes in list
            var checkedCheckboxes = $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox:checked").size();
            //Check / Uncheck top checkbox if all the checked boxes in list are checked
            $("#<%=gvEmployees.ClientID%> input[id*='chkAll']:checkbox").attr('checked', totalCheckboxes == checkedCheckboxes);
        });

        $("#<%=gvEmployees.ClientID%> input[id*='chkAll']:checkbox").click(function () {
            //Check/uncheck all checkboxes in list according to main checkbox 
            $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox").attr('checked', $(this).is(':checked'));
        });
    });
</script>

   

Thanks and regards.   

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Nassermalek

United States United States
No Biography provided

Comments and Discussions

 
Answercheck uncheck gridview checkboxes using jquery Pinmembervaraprasadreddy.bh23-Sep-12 8:26 
GeneralMy vote of 1 PinmemberVitaly Tomilov6-Sep-12 12:26 
Question[My vote of 1] this is just too awful PinmemberSeishin#17-Jul-12 4:43 
AnswerRe: [My vote of 1] this is just too awful PinmemberNassermalek17-Jul-12 5:18 
GeneralRe: [My vote of 1] this is just too awful PinmemberVitaly Tomilov6-Sep-12 12:23 
AnswerRe: [My vote of 1] this is just too awful Pinmemberdotnetpickles12-Feb-14 0:58 
GeneralRe: [My vote of 1] this is just too awful PinmemberNassermalek14-Feb-14 7:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140827.1 | Last Updated 2 Aug 2013
Article Copyright 2012 by Nassermalek
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid