Javascript tips
Select/Deselect a bunch of checkboxes using jQuery
September 26, 2012

Hi to everyone,

I’d like to show what’s my solution to Select/deselect a group of check boxes in a form.

First of all we need something with some check boxes in it, and here is a table which suits our purposes:

<table id="authors" style="border-collapse: collapse;" border="1">
<th><input type="checkbox" id="checkall" onclick="checkUncheckAll('checkall');"></th>
<td><input id="author1" type="checkbox" value="1" /></td>
<td>Dante Alighieri</td>
<td>Divine Comedy</td>
<td><input id="author2" type="checkbox" value="2" /></td>
<td>Stephen King</td>
<td>The Shining</td>
<td><input id="author3" type="checkbox" value="3" /></td>
<td>Robert Doherty</td>
<td>Area 51</td>
<td><input id="author4" type="checkbox" value="4" /></td>
<td>Isaac Asimov</td>

Now the question is, how do we select or deselect all the check boxes?

There are two ways of doing it, one is “plain old JavaScript” the other is jQuery; today I will focus on Wildeng’s jQuery way!!!

So first we have to find out the id of the table which contains our “stuff” and the status of the ‘checkall’  switch, which is the check box in the upper left corner of our table header,  used to activate the select/deselect function. :

tableId = $('#checkall').closest('table').attr('id');
curStatus = false;
if($('#'+currentId).attr('checked') =='checked' ){
     curStatus = true;
     curStatus = false;

At this point we have everything we need to find all the checkboxes, loop among them and change their status:

$('#' + tableId).find(':input:checkbox').each(function(index) {
		if($(this).attr('id') != 'checkall'){
			$(this).attr('checked', curStatus);

Now is up to you what to do with the selected check boxes; you could, for example, get all their ids and use them to update a shopping cart, delete them from a database or whatever your application needs to do with them.

Here is the complete code for the example:


Happy coding!!

Leave a Reply

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.