Checking All CheckBoxes in a GridView Using jQuery

Published 04 December 10 02:41 AM | Scott Mitchell

How do I love thee, jQuery? Let me count the ways.

In May 2006 I wrote an article on 4GuysFromRolla.com titled Checking All CheckBoxes in a GridView Using Client-Side Script and a Check All CheckBox, in which I showed how to add a column of checkboxes to a GridView along with a checkbox in that column’s header that enabled the user to check/uncheck all checkboxes in one fell swoop. This check/uncheck all functionality was accomplished using JavaScript.

While the JavaScript presented in the article worked then (and still works today, of course), it is a less than ideal approach for a couple of reasons.

  • First, each checkbox in the grid is programmatically assigned a client-side onclick event handler in the GridView’s DataBound event handler that calls a function that determines whether to check or uncheck the checkbox in the head – having a client-side event handler defined directly in an HTML element violates the design goal of unobstrusive JavaScript.
  • Second, because programmatically assigned client-side attributes are not remembered across postbacks and because these client-side attributes are only assigned when data is bound to the grid, the script is lost when there is a postback that doesn’t cause the grid to have its data re-bound to it. Long story short, the check/uncheck all functionality stops working after such postbacks. I provide a workaround for this, but it’s extra steps, extra script, and another thing that you have to remember to do.
  • Third, the solution entails quite a bit of script, much more than is necessary using modern JavaScript libraries.

When I authored the article jQuery had not yet been released. Fortunately, today we have jQuery (and other JavaScript libraries) at our fingertips. jQuery is a free, open-source JavaScript library created by John Resig. In a nutshell, jQuery allows us to accomplish common client-side tasks with terse, readable script. With jQuery, I can rewrite the entire GridView check/uncheck all functionality with zero lines of server-side code and a scant 25 or so lines of JavaScript.

To demonstrate jQuery’s power, consider a GridView with the following markup:

<asp:GridView ID="gvProducts" runat="server" ...>
    <Columns>
        <asp:TemplateField>
            <HeaderTemplate>
                <asp:CheckBox runat="server" ID="chkAll" />
            </HeaderTemplate>
            <ItemTemplate>
                <asp:CheckBox runat="server" ID="chkSelected" />
            </ItemTemplate>
        </asp:TemplateField> 
        ...
    </Columns>
</asp:GridView>

Note the TemplateField – this is where the two CheckBox controls live. The CheckBox control in the HeaderTemplate (chkAll) is the check/uncheck all checkbox, while the CheckBox control in the ItemTemplate (chkSelected) is the checkbox that appears in each of the grid’s data rows.

Now, I need script that does the following:

  1. When one of the chkSelected checkboxes is checked or unchecked, I need to determine whether the all option needs to be checked or unchecked. In the case where all chkSelected checkboxes are checked, I want to check chkAll. Likewise, in the case when any chkSelected checkbox is unchecked, I want to uncheck chkAll.
  2. When chkAll is checked or unchecked, I need to check or uncheck all chkSelected checkboxes.

To address the first concern I created a function named CheckUncheckAllCheckBoxAsNeeded. This function determines the total number of chkSelected checkboxes in the grid and the number of checked chkSelected checkboxes. If the two numbers match then chkAll is checked, otherwise it’s unchecked.

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

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

This function is executed whenever one of the chkSelected checkboxes is checked or unchecked. This event wiring is handled in the $(document).ready event handler. Also, the CheckUncheckAllCheckBoxAsNeeded function is called right off the bat in case the grid’s checkboxes are already all checked when the page loads.

$(document).ready(function () {
    $("#<%=gvProducts.ClientID%> input[id*='chkSelected']:checkbox").click(CheckUncheckAllCheckBoxAsNeeded);

    ...

    CheckUncheckAllCheckBoxAsNeeded();
});

Finally, we need to check/uncheck all chkSelected checkboxes when chkAll is checked or unchecked. This logic is also in the $(document).ready event handler (where the ellipsis is positioned in the above snippet).

$("#<%=gvProducts.ClientID%> input[id*='chkAll']:checkbox").click(function () {
    if ($(this).is(':checked'))
        $("#<%=gvProducts.ClientID%> input[id*='chkSelected']:checkbox").attr('checked', true);
    else
        $("#<%=gvProducts.ClientID%> input[id*='chkSelected']:checkbox").attr('checked', false);
});

Pretty neat and a whole heck of a lot simpler than the technique I initially showcased in Checking All CheckBoxes in a GridView Using Client-Side Script and a Check All CheckBox. A more detailed look at this code, along with a downloadable working example, will be on 4Guys within the next couple of weeks.

UPDATE [2010-12-07]: A 4Guys article that provides much more detail and screen shots and a downloadable demo is now available: Checking All Checkboxes in a GridView Using jQuery. Also, special thanks to Elijah Manor, who offered a number of suggestions on how to improve and tighten up my jQuery script.

Happy Programming!

Filed under: ,

Comments

No Comments

Archives

My Books

  • Teach Yourself ASP.NET 4 in 24 Hours
  • Teach Yourself ASP.NET 3.5 in 24 Hours
  • Teach Yourself ASP.NET 2.0 in 24 Hours
  • ASP.NET Data Web Controls Kick Start
  • ASP.NET: Tips, Tutorials, and Code
  • Designing Active Server Pages
  • Teach Yourself Active Server Pages 3.0 in 21 Days

I am a Microsoft MVP for ASP.NET.

I am an ASPInsider.