Tuesday, 27 November 2012

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. Sivani ",     Address = "507 - 20th Ave. E.  Apt. 2A",    Designation = "Sales Representative"},
        new Employee(){ Id = 2, Name = "Dr. Ramesh Kumar",     Address = "908 W. Capital Way",             Designation = "Vice President Sales"},
        new Employee(){ Id = 3, Name = "Ms. Rekha",   Address = "722 Moss Bay Blvd.",             Designation = "Sales Representative"},
        new Employee(){ Id = 4, Name = "Mrs. sangita ", Address = "4110 Old Redmond Rd.",           Designation = "Sales Representative"},
        new Employee(){ Id = 5, Name = "Mr. Hemant ",   Address = "14 Garrett Hill",                Designation = "Sales Manager"},
        new Employee(){ Id = 6, Name = "Mr. Rohit ",    Address = "Coventry House  Miner Rd.",      Designation = "Sales Representative"},
        new Employee(){ Id = 7, Name = "Mr. Rahul ",       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 
 
<Sort<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 () {
    if ($(this).is(':checked'))
        $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox").attr('checked', true);
    else
        $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox").attr('checked', false);
});
 
2. On each of the list CheckBox checked/unchecked, we have to determine Check/Uncheck top CheckBox.  
 
 function CheckUncheckAllCheckBoxAsNeeded() {
        var totalCheckboxes = $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox").size();
        var checkedCheckboxes = $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox:checked").size();

        if (totalCheckboxes == checkedCheckboxes) {
            $("#<%=gvEmployees.ClientID%> input[id*='chkAll']:checkbox").attr('checked', true);
        }
        else {
            $("#<%=gvEmployees.ClientID%> input[id*='chkAll']:checkbox").attr('checked', false);
        }
    }
 
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(CheckUncheckAllCheckBoxAsNeeded);
        $("#<%=gvEmployees.ClientID%> input[id*='chkAll']:checkbox").click(function () {
            if ($(this).is(':checked'))
                $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox").attr('checked', true);
            else
                $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox").attr('checked', false);
        });
    });

    function CheckUncheckAllCheckBoxAsNeeded() {
        var totalCheckboxes = $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox").size();
        var checkedCheckboxes = $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox:checked").size();

        if (totalCheckboxes == checkedCheckboxes) {
            $("#<%=gvEmployees.ClientID%> input[id*='chkAll']:checkbox").attr('checked', true);
        }
        else {
            $("#<%=gvEmployees.ClientID%> input[id*='chkAll']:checkbox").attr('checked', false);
        }
    }
</script>
 
  
 



 
 
 

No comments :