jQuery plugin for SELECT ALL check boxes

Here’s a simple jQuery plugin for implementing a “Select All” checkbox.

Usage:

checkboxes.checkAll(allSelector)

where:

  • checkboxes –  jQuery object for the set of checkboxes to control
  • allSelector – CSS selector string to match the “select all” checkbox

Example:

<input id="all" type="checkbox" name="all"></input>Select All<br />
<div id="myCheckBoxes">
<input type="checkbox" name="1"></input>1<br />
<input type="checkbox" name="2"></input>2<br />
<input type="checkbox" name="3"></input>3
</div>
<script type="text/javascript">
$(function() {
$("#myCheckBoxes input").checkAll("#all");
});
</script>

Plug-In Code:

;(function($) {
	$.fn.checkAll = function checkAll(allSelector) {
		var all = $(allSelector);
		var items = this;

		all.click(function() {
			if (all.get(0).checked)
				items.attr("checked", "checked");
			else
				items.removeAttr("checked");
		});

		function evalAllChecked() {
			if (items.filter(":checked").length == items.length)
				all.attr("checked", "checked");
			else
				all.removeAttr("checked");
		}

		evalAllChecked();
		items.click(evalAllChecked);
	}
})(jQuery);
Advertisement

About this entry