I've been working with JQuery quite a bit lately and I'm aggravated that I didn't pick it up sooner. Someone on the DFW CFUG mailing list asked for a quick example of why they should use it. Another post on the JQuery list asked how to create a "Check All" box using JQuery. I decided to expand on the "check all" example I posted to the CFUG list to show how things have progressed from old school Javascript to JQuery.

Updated 4/18/2012

An updated version of this post was released in April 2012. Comments for this entry have been disabled.

Working Examples

So here's a basic form with 2 series of checkboxes.

myCB yourCB
A
B
C
D
E
F
G
H
I
J
K
L

1.

2.

3. Check All checkboxes with JQuery Automatically

4a. Check All named "myCB" with JQuery onclick.

4b. Check All named "yourCB" with JQuery onclick.

5a. JQuery Check All Left Column

5b. JQuery Uncheck All Right Column

Break It Down: Old School to JQuery

Each column in the form has a group of checkboxes of the same name. When you have multiple form elements of the same name, they represent an Array in the Document Object Model (DOM).

view plain print about
1<form id="myForm" name="myForm" action="" method="post">
2    <table border="1">
3        <tr>
4            <td>myCB</td>
5            <td>yourCB</td>
6        </tr>
7        <tr>
8            <td>
9                <input type="checkbox" name="myCB" value="A" /> A<br />
10                <!-- etc. -->
11            </td>
12            <td>
13                <input type="checkbox" name="yourCB" value="G" /> G<br />
14                <!-- etc. -->
15            </td>
16        </tr>
17    </table>

1. Old School

The first set of buttons will check and uncheck all checkboxes named myCB.

view plain print about
1<input type="button" name="ca_v1_on" value="Check All myCB" onclick="checkAll(1);"/>
2<input type="button" name="ca_v1_off" value="Uncheck All myCB" onclick="checkAll(0);"/>

These buttons call the Javascript function checkAll() when you click them. This function determines if there is more than one form element named myCB. If so, then it loops through those elements, setting their checked attribute to true or false based on the value of flag. If there's only one, then it sets that one element's checked attribute to true or false based on the value of flag.

checkAll() - Old School Javascript
view plain print about
1function checkAll(flag)
2{
3    if ( document.myForm.myCB.length )
4    {
5        for (var x = 0; x < document.myForm.myCB.length; x++)
6        {
7            if (flag == 1)
8            {
9                document.myForm.myCB[x].checked = true;    
10            }
11            else
12            {
13                document.myForm.myCB[x].checked = false;
14            }
15            
16        }
17    }
18    else
19    {
20        if (flag == 1)
21        {
22            document.myForm.myCB.checked = true;                
23        }
24        else
25        {
26            document.myForm.myCB.checked = false;
27        }
28    }
29}

That's a boat load of code. We could remove some of the hard coded bits like this:

view plain print about
1function checkAll(id, name, flag)
2{
3    if ( document.forms[ id ].elements[ name ].length )
4    /* ... */
5}

or even using

view plain print about
1function checkAll(id, name, flag)
2{
3    if ( document.getElementsById( id ).elements[ name ].length )
4    /* ... */
5}

but it's still a lot of code.

2. Stepping into JQuery

The second set of buttons will check or uncheck all checkboxes named myCB using JQuery.

view plain print about
1<input type="button" name="ca_v2_on" value="JQuery Check All myCB" onclick="jqCheckAll('myForm', 'myCB', 1);"/>
2<input type="button" name="ca_v2_off" value="JQuery Uncheck All myCB" onclick="jqCheckAll('myForm', 'myCB', 0);"/>

These buttons call the Javascript function jqCheckAll(). This function takes three arguments:

  1. The ID of the form that contains the checkboxes.
  2. The name of the checkboxes that will be checked.
  3. A flag to check (1) or uncheck (0) each checkbox.

jqCheckAll() - JQuery
view plain print about
1function jqCheckAll( id, name, flag )
2{
3    if (flag == 0)
4    {
5        $("form#" + id + " INPUT[@name=" + name + "][type='checkbox']").attr('checked', false);
6    }
7    else
8    {
9        $("form#" + id + " INPUT[@name=" + name + "][type='checkbox']").attr('checked', true);
10    }
11}

Let's break down the JQuery code's syntax:

view plain print about
1$("form#" + id + " INPUT[@name=" + name + "][type='checkbox']").attr('checked', false);

  1. $("form#" + id: Find a form whose ID is the value of the id argument.
  2. " INPUT[@name=" + name + "]: now find any INPUT element whose name matches the value of the name argument.
  3. [type='checkbox']: make sure that form element is of type "checkbox".
  4. .attr('checked', false);: set that element's checked attribute to true or false based on the value of the argument flag.

Ok, so that's a LOT less code. We also don't have to worry about there being one element or an array of elements. JQuery handles that for us.

3. Let JQuery handle things automatically.

Our third option for checking all these checkboxes involves a single form element. We don't even have to add any onclick or onchange events directly to the checkbox. JQuery will let us assign that outside of the HTML.

view plain print about
1<input type="checkbox" name="checkAllAuto" id="checkAllAuto"/> Check All checkboxes with JQuery Automatically

Here we don't write a traditional Javascript function. Instead, we tell JQuery to assign a click event to a particular DOM object ( id="checkAllAuto" ). In that event, we will then define and run a function.

$( id ).click()
view plain print about
1$('#checkAllAuto').click(
2    function()
3    {
4        $("INPUT[type='checkbox']").attr('checked', $('#checkAllAuto').is(':checked'));    
5    }
6)

By not placing this code inside a defined function, we're defining the onclick event for the form element checkAllAuto when the page loads.

The line of JQuery inside the click event is broken down like this:

  1. $("INPUT[type='checkbox']"): Find all form elements of type "checkbox"
  2. .attr('checked', $('#checkAllAuto').is(':checked'));: and set their attribute checked to true or false
  3. $('#checkAllAuto').is(':checked'): based on the checked value of the form element checkAllAuto.

Wow! That's even less code. But there's a problem in that this code check or unchecks every checkbox in the form since we didn't specify a name attribute to find.

4. Merging options 2 and 3

Finally, we can merge the techniques used in the last two examples to check or uncheck multiple groups of checkboxes in the same form.

view plain print about
1<p>4a.
2    <input type="checkbox" name="checkAllMyCB" id="checkAllMyCB" onclick="jqCheckAll2( this.id, 'myCB' )"/> Check All named "myCB" with JQuery onclick.
3</p>
4    
5<p>4b.
6    <input type="checkbox" name="checkAllYourCB" id="checkAllYourCB" onclick="jqCheckAll2( this.id, 'yourCB' )"/> Check All named "yourCB" with JQuery onclick.
7</p>

These two checkboxes will each mark a specific named group of checkboxes based on their own checked status.

jqCheckAll2()
view plain print about
1function jqCheckAll2( id, name )
2{
3    $("INPUT[@name=" + name + "][type='checkbox']").attr('checked', $('#' + id).is(':checked'));
4}

Broken down:

  1. $("INPUT[@name=" + name + "]: Find all INPUT elements whose name is the value of the name argument.
  2. [type='checkbox']"): and whose element type is checkbox
  3. .attr('checked', $('#' + id).is(':checked'));: and mark its checked attribute as true or false based on the checked status of the form element id.

5. I forgot your name (Added 7/16/2008)

You don't even have to use names or IDs on the checkboxes you want to check. All you need is the ID of their parent container. I've updated the FORM to add an ID to the two TDs that contain the groups of checkboxes.

view plain print about
1<td id="left"><!-- check boxes --></td>
2<td id="right"><!-- check boxes --></td>

And two more checkboxes to trigger checking any checkboxes they contain:

view plain print about
1<p>5a.
2    <input type="checkbox" id="checkL" onclick="jqCheckAll3(this.id, 'left');"/> JQuery Check All Left Column
3</p>
4<p>5b.
5    <input type="checkbox" id="checkR" onclick="jqCheckAll3(this.id, 'right');"/> JQuery Uncheck All Right Column
6</p>

And the function they call:

jqCheckAll3()
view plain print about
1function jqCheckAll3( id, pID )
2{
3    $( "#" + pID + " :checkbox").attr('checked', $('#' + id).is(':checked'));
4}

Broken down:

  1. $( "#" + pID: Find the element with this ID (could be a DIV, SPAN, FIELDSET, etc.)
  2. + " :checkbox"): and for all elements of type "checkbox" inside that element,
  3. .attr('checked', $('#' + id).is(':checked'));: mark their checked attribute as true or false based on the checked status of the form element id.

re: #1, you could even get more specific by saying:

view plain print about
1$("TD#" + pID)

re: #2, I replaced [type='checkbox'] with " :checkbox" based on Richard's comment.

Summary

Hopefully, this simple (?!) example shows some of the power of the JQuery library. Give it a try when you start your next project or even better, see how you might incorporate it in an existing one. Once you get the basics down, you may find that you can get more done faster and with less code than you could by sticking to Old School Javascript.

References

The JQuery website
JQuery Google Group
DFW CFUG Google Group
JQuery Docs: Attributes/attr
JQuery Docs: Selectors/checked

I found the solution $('#' + id ).is(':checked'); here.