Location > Blog

Toggle multiple checkboxs using JQuery with ASP.NET

In one of my projects I had a button to toggle a collection of check boxes output from a CheckBoxList control on the page. Initially I toggled these with a server postback.

Later on I though that was fairly lazy it should really be done with some client side JavaScript. I have been using JQuery recently and I figured it should make this quite easy and it is.

The ASPX markup

 
    <asp:CheckBoxList ID="CheckBoxList1" CssClass="togglelist" runat="server"
        <asp:ListItem>item 1</asp:ListItem> 
        <asp:ListItem>item 2</asp:ListItem> 
        <asp:ListItem>item 3</asp:ListItem> 
    </asp:CheckBoxList> 
    <asp:HyperLink ID="ToggleList" runat="server" cssclass="togglebutton" NavigateUrl="javascript:void(0);" Text="All / None" /> 
                     

The toggle JavaScript using a class selector

 
    $(document).ready(function() 
    { 
        $(".togglebutton").toggle( 
          function () { 
            $(".togglelist input:checkbox").attr("checked","checked"); 
          }, 
          function () { 
            $(".togglelist input:checkbox").removeAttr("checked"); 
          } 
        ); 
    }); 
 

I have chosen to use a class selector rather than using the CheckBoxList1 ID because the checkbox control is in a User Control nested in a page, so I would have had to write some C# code to obtain the value of the CheckBoxList1.ClientID property.

This method works fine unless your User Controls is loaded in a AJAX Panel after the initial page load. The JavaScript inside the AJAX Panel is not loaded because there is no onload event. So I had to modify the method to fire when the button was clicked.

The C# Code

 
    ScriptManager.RegisterClientScriptBlock(Page, typeof(Export), "REG_TOGGLE_VAR""var toggle=true;"true); 
    ToggleList.Attributes["onclick"] = string.Concat("$(\".togglelist input:checkbox\").attr(\"checked\",toggle);toggle=!toggle;"); 
 
 

There is also a JQuery checkboxes plugin that allows you to toggle, check or uncheck checkboxes.

Saturday January 17 2009 10:48 a.m.