jQuery Checkboxes: Select All, Select None, and Invert Selection

A demonstration of selecting checkboxes using jQuery.We start off with a bunch of checkboxes:

[sourcecode language=”html”]<input type="checkbox" name="numbers[]" value="0" />
<input type="checkbox" name="numbers[]" value="1" />
<input type="checkbox" name="numbers[]" value="2" />
<input type="checkbox" name="numbers[]" value="3" />
<input type="checkbox" name="numbers[]" value="4" />
<input type="checkbox" name="numbers[]" value="5" />
<input type="checkbox" name="numbers[]" value="6" />
<input type="checkbox" name="numbers[]" value="7" />
<input type="checkbox" name="numbers[]" value="8" />
<input type="checkbox" name="numbers[]" value="9" />[/sourcecode]

Now, we add some links:

[sourcecode language=”html”]<a rel="group_1" href="#select_all">Select All</a>
<a rel="group_1" href="#select_none">Select None</a>
<a rel="group_1" href="#invert_selection">Invert Selection</a>[/sourcecode]

The rel attribute is equal to the ID of the containing element of the checkbox group. In this example the containing element is a fieldset, but it could be a DIV, P, UL, etc.

Now, we add behaviors using jQuery:

[sourcecode language=”html”]<script type="text/javascript">
$(document).ready( function() {
// Select all
$("A[href=’#select_all’]").click( function() {
$("#" + $(this).attr(‘rel’) + " INPUT[type=’checkbox’]").attr(‘checked’, true);
return false;
});
// Select none
$("A[href=’#select_none’]").click( function() {
$("#" + $(this).attr(‘rel’) + " INPUT[type=’checkbox’]").attr(‘checked’, false);
return false;
});
// Invert selection
$("A[href=’#invert_selection’]").click( function() {
$("#" + $(this).attr(‘rel’) + " INPUT[type=’checkbox’]").each( function() {
$(this).attr(‘checked’, !$(this).attr(‘checked’));
});
return false;
});
});
</script>[/sourcecode]

To add the same functionality to another group of checkboxes, create more links and adjust the rel attribute accordingly:

[sourcecode language=”html”]<a rel="group_2" href="#select_all">Select All</a>
<a rel="group_2" href="#select_none">Select None</a>
<a rel="group_2" href="#invert_selection">Invert Selection</a>[/sourcecode]
[sourcecode language=”html”]<a rel="group_3" href="#select_all">Select All</a>
<a rel="group_3" href="#select_none">Select None</a>
<a rel="group_3" href="#invert_selection">Invert Selection</a>

…[/sourcecode]

Leave a Reply