Saturday, March 21, 2009

make ASP.Net CheckBoxList mutually exclusive using jQuery

I ran across a stupid problem a few days ago trying to make an ASP.Net CheckBoxList control be mutually exclusive. ASP.Net Ajax has an extender that makes checkbox's mutually exclusive. The problem with it, is that it works with individual checkbox controls, not a CheckBoxList control. I did not want to make them all separate controls because I was binding them to a datasource, and I wanted it to lay out the checkboxes the way it does.

The way the CheckBoxList works makes it impossible to use (maybe I am wrong on this) the ASP.Net Ajax extender control. So my next thought was to write up some javascript to only allow one item to be selected out of all the checkboxs. Since the CheckBoxList controls wraps all the ListItem's in a table (I think it has an inline way to render as well) and that it all has auto generated ID's it makes it hard to write a little custom javascript method to attach to each checkboxes click event.

Then comes jQuery to the rescue! I have been using jQuery recently, and found that its selector helps out ASP.Net development immensly. Because we have such little control of how the HTML renders using the default ASP.Net controls, it makes it hard to apply styles and client side javascript. Below is a small method I modified from someone else to go through and make only one of the checkbox's be able to be in the checked state at a time.

/* This is used to make a list of checkboxes to become
mutually exclusive */
(function($) {
$.fn.makeCheckboxesMutuallyExclusive = function() {
//list of checkboxes
var checkBoxes = this.filter('input:checkbox');
//add a click function to each one to make sure one is checked
checkBoxes.click(function() {
checkedState = $(this).attr('checked');
//loop on all checkboxes and uncheck them
$(checkBoxes).each(function() {
$(this).attr('checked', false);
});
$(this).attr('checked', checkedState);
});
}
})(jQuery);
Take the following snippet of code from an ASPX page, and assume its being bound to a datasource that will populate its list items automatically.

<asp:checkboxlist runat="server" id="chkExample" repeatdirection="Horizontal"></asp:CheckBoxList>


We can then write some javascript to make all the checkboxes in this list mutually exclusive. It looks like this.

$('#<%=chkExample.ClientID %> td input').makeCheckboxesMutuallyExclusive();
This should select all the input controls inside the table that the CheckBoxList wraps its contents in. It then calls the function above with those items to make them mutally exclusive.