jQuery Check & Uncheck All



Go here for an updated version of this script!


I googled around a bit for a simple solution to use check/uncheck all checkboxes using jQuery today but I couldn’t find a simple generic solution to the problem so I wrote my own instead.
It will keep track of multiple instances of check all groups on the same page and toggle the status of the boxes when clicked multiple times.

HTML Mark-up
First off you’ll need a bit of html: A couple of check boxes and a select all box.
A couple of things to consider in the mark up:
1. The class of the checkboxes must be the same as the value of the select all for that group.
2. The id of the select-all box must correspond to the id of the div layer containing the status.

<input class="group_1" name="boxes_1[]" value="somevalue_1" />Checkbox 1
<input class="group_1" name="boxes_1[]" value="somevalue_2" />Checkbox 2
<input class="group_1" name="boxes_1[]" value="somevalue_3" />Checkbox 3
<input type="checkbox" class="nn-checkall" value="group_1" id="checkall_1" />Select/Deselect All
<div id="checkall_1_status">true</div>

<input class="group_2" name="boxes_2[]" value="whatever_1" />Checkbox 1
<input class="group_2" name="boxes_2[]" value="whatnot_2" />Checkbox 2
<input type="checkbox" class="nn-checkall" value="group_2" id="checkall_2" />Select/Deselect All
<div id="checkall_2_status">true</div>

The jQuery Code
The value of the select-all keeps track of which boxes to toggle.
Using the id of the select-all we get the current status from the div layer.

$(document).ready(function()
{
	$('.nn-checkall').click(function()
	{
		var $sClass = $(this).val();
		var $check = $('#' + $(this).attr('id') + '_status').text();
		if($check == 'true')
		{
			$('input[@type=checkbox].' + $sClass).attr('checked', 'checked');
			$('#' + $(this).attr('id') + '_status').text('false');
		}
		else
		{
			$('input[@type=checkbox].' + $sClass).removeAttr('checked');
			$('#' + $(this).attr('id') + '_status').text('true');
		}
	});
});

Finally I just want to add that you probably want to hide the status layer using css (display:none;) and that the mark-up validates against W3C.
I’d also like to add that this solution can be improved and made even more dynamic if you’d like. It would be very simple to add a parent div layer and not have to add classes to the boxes for example but I chose this mark up mainly because it is unobtrusive. After all, div layers has properties of its own… Cheerio :)

Write Comment

CAPTCHA image


Comment Preview


#

10 Most Recent Twits

Loading twits...