Select and Unselect All Checkboxes with jQuery

I’ve been working with jQuery to spice up my interfaces for over 12 months now and figured it’s time to share some of the little techniques I’ve developed on the way.


The first is something I use quite alot when I am giving users the ability to administer lists of items in bulk. That including a checkbox that when checked sets the state of all the checkboxes beside a list of items to “checked”. Naturally unchecking it will uncheck all checkboxes. I’m sure you get the picture here’s the code based on two scenarios depending on your preference. But firstly you need to include the jQuery library in the head of your document (I grab mine straight from Google’s repository to save my bandwidth):

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>

and then somewhere in your document a controller checkbox that toggles all the others (note the call to toggleChecked when the state of the checkbox changes):

<input type="checkbox" onclick="toggleChecked(this.checked)"> Select / Deselect All

Now here are  two versions of the toggleChecked function dependent on the semantics of your document. The only real difference is the jQuery selector for your list checkboxes:

1: All checkboxes have a class of  “checkbox” (<input type=”checkbox” class=”checkbox” />)
function toggleChecked(status) {
$(".checkbox").each( function() {
$(this).attr("checked",status);
})
}

2: All the checkboxes are contained within a div with an arbitary id:

<div id="checkboxes">
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</div>

In this case the function would look like this:

function toggleChecked(status) {
$("#checkboxes input").each( function() {
$(this).attr("checked",status);
})

Leave a comment