Select All Items in asp.net CheckBoxList

splatto picture splatto · Mar 22, 2011 · Viewed 19k times · Source

ASP.NET and C#.

I'd like to have a CheckboxList with a "Select All" item.

  • When this particular item is selected, all others will be selected too.
  • When selection is removed from this item, so too will it be from all others items.
  • Checking/Unchecking of any other items will only have an effect on that particular item regardless of the selection state of "Select All" item.

I am looking for a jquery solution to this.

Here is the databinding code in my codebehind:

IList<Central> Centrals = new CentralProvider().GetAllCentralsAsList();
Centrals.Insert(0, new Central(){Central_ID = 999, Central_Name = "Select All"});
CentralChecks.DataSource = Centrals;
CentralChecks.DataTextField = "Central_Name";
CentralChecks.DataValueField = "Central_ID";
CentralChecks.DataBind();

And here is the markup:

<div class="CentralDiv" id="CentralDiv">
    <h2>Centrals:</h2>
    <span>
        <asp:TextBox ID="CentralTextBox" runat="server" CssClass="textbox">Centrals</asp:TextBox>
        <img id="CentralArrow" src="images/down_arrow.jpg" style="margin-left: -22px; margin-bottom: -5px" />
    </span>
    <div id="CentralEffect" class="ui-widget-content">
        <asp:CheckBoxList ID="CentralChecks" runat="server" onclick="GetSelectedCentralValue();">
        </asp:CheckBoxList>
    </div>
</div>

Note that there are multiple checkbox lists on the page, so any solution must keep this in mind.

Answer

MikeM picture MikeM · Mar 22, 2011

Something like you could use for any of your checkbox lists, just add a cssclass of myCheckBoxList to each CheckBoxList control:

$('.myCheckBoxList :checkbox').eq(0).click(function() { 
    var toggle = this.checked;
    $('.myCheckBoxList :checkbox').attr("checked", toggle);
});