Guy Harwood

UK based developer

Toggle items in a CheckBoxList using jQuery

Just a little snippet of jQuery that i find useful for toggling selection of items in an asp.net CheckBoxList control.

  1. Set the CssClass of your CheckBoxList to recipientList
  2. Add a reference in your page/master to jQuery
  3. Add the following javascript into your page header..
function toggleChecks(b) {
$(".recipientList input[type=checkbox]").each(function() {
if (typeof this.checked != "undefined") {
if (b == null)
this.checked = (!this.checked);
else
this.checked = b;
}
});
}

Now you can have 3 links/buttons/images alongside your CheckBoxList – One to toggle the checked state of all checkboxes, one to set all checkboxes to checked, and finally one to uncheck all checkboxes. 

Setting the parameter ‘b’ to null means ‘toggle the state’, true = checked and false = unchecked.

My HTML for the links looks like this…

<a id="selectAll" class="selectionToggle" onclick="toggleChecks(true);return false;" href="#">Select All</a>
<a id="selectNone" class="selectionToggle" onclick="toggleChecks(false);return false;" href="#">Select None</a>
<a id="toggle" class="selectionToggle" onclick="toggleChecks(null);return false;" href="#">Invert Selection</a>

You can very easily wire the Javascript function into a jQuery plugin for all your projects.

kick it on DotNetKicks.com

Comments

DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# November 21, 2008 4:48 AM

Alex Walsh said:

Hey, thanks a bunch for this. I was looking for some time for a solution to my problem, I was unable to get jQuery to select my checkbox, your "input[type=checkbox]" solved my problem. Thanks a million!!

# March 31, 2009 10:11 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)