Mutually Exclusive CheckBoxList

ASP.NET provides two useful server controls that allows one to choose from several available options, the CheckBoxList and RadioButtonList controls. The functionality of these controls is very similar and the primary difference is that the CheckBoxList allows multiple items to be selected where as the RadioButtonList only allows one item to be selected. There is one quirk with the RadioButtonList, once a selection is made it cannot be removed, by default. Recently a client asked if we could implement a CheckBoxList that included the the functionality of a RadioButtonList where a given option could be removed, but the options were mutually exclusive. Thanks to jQuery, implementing the desired behavior was relatively easy.

Below is an example of the HTML markup along with the jQuery code that was used.

<form id="frmOptions" runat="server">
<div class="divOptions">
    <asp:CheckBoxList ID="cblOptions" runat="server" class="cbl">
        <asp:ListItem Text="Option 1" Value="1" />
        <asp:ListItem Text="Option 2" Value="2" />
        <asp:ListItem Text="Option 3" Value="3" />
        <asp:ListItem Text="Option 4" Value="4" />
        <asp:ListItem Text="Option 5" Value="5" />
    </asp:CheckBoxList>
    <br />
    <br />
    <h3 class="subHeader" style="margin: 0">Note:</h3>
    <ul id="notes" style="margin-top: 0">
        <li>Clicking on any of the individual checkboxes, clears the previous selection.</li>
        <li>Clicking the same checkbox toggles the selection (default behavior).</li>
    </ul>
</div>
</form>
$(function () {
    // get all the checkboxes
    var $tblChkBox = $("table.cbl input:checkbox");

    // add a click handler to each checkbox
    $tblChkBox.click(function () {
        // get the id of the selected checkbox
        var selectedId = this.id;

        // uncheck all checkboxes except the selected one
        $tblChkBox.each(function () {
            if(this.id != selectedId) this.checked = false;
        });
    });
});

In this example, once the page loads and the document is ready, all the input elements of the checkbox type within the table are located based on the css class “cbl”. Note the checkboxlist renders as an HTML table. A click event handler is then added to each checkbox to clear the other checkboxes and the default toggle behavior of the selected checkbox is maintained.

If you’re new to jQuery, the Getting Started with jQuery tutorials are a good place to start. Rick Strahl also has a great introduction to jQuery article and the Learning jQuery site is excellent with categories/filters based on your skill level.

Tags: , , , ,

  • Delicious
  • Facebook
  • Digg
  • Reddit
  • LinkedIn
  • StumbleUpon
  • Twitter

Leave a Reply