Pages

Select rows using header checkbox in gridview

Here I am going to show a simple jQuery code that selects all the checkboxes from grid rows when header checkbox is selected. This is pretty common requirement. Also the code toggles header checkbox depending on whether all the rows have been selected.


Consider a sample gridview markup as shown below:
<asp:GridView ID="GridView1" runat="server" DataKeyNames="ID">
    <Columns>
        <asp:TemplateField>
            <HeaderTemplate>
                <asp:CheckBox runat="server" ID="chkHeader" CssClass="header_checkbox" />
            </HeaderTemplate>
            <ItemTemplate>
                <asp:CheckBox runat="server" ID="chkItem" CssClass="item_checkbox" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
The CSS classes "header_checkbox" and "item_checkbox" are used by jQuery code to select all the matching checkboxes. This is because you cannot select checkboxes by simply using checkbox IDs as asp.net alters the ID of the controls. You may define style properties in these classes or even leave them blank but make sure you define those classes.
<style type="text/css">
    .header_checkbox { }
    .item_checkbox { }
</style>
Now is the time for real part, our jQuery code. It is very simple code and hence I don't feel need to explain much about it! Its self explanatory.
$(document).ready(function () {
    // Get checkbox in header
    var chkHeader = $(".header_checkbox input[type='checkbox']");
    // Get checkboxes in rows
    var chkInput = $(".item_checkbox input[type='checkbox']");
    // Counter
    var ctr = 0;

    // Toggle header checkbox
    chkInput.each(function () {
        $(this).click(function () {
            if (this.checked) ctr++;
            else ctr--;

            if (ctr == chkInput.length)
                chkHeader.attr('checked', 'checked');
            else
                chkHeader.removeAttr('checked');
        });
    });

    // Toggle row checkboxes
    chkHeader.click(function () {
        chkInput.each(function () {
            this.checked = chkHeader.attr('checked');
        });
    });
});

No comments:

Post a Comment