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

No Comments