Note: [@attr] selectors are no longer supported by jQuery 1.3.x and above. Use [attr] instead
Here is a simple tutorial on how to implement the “select all” function for checkboxes in jQuery. All you need to know for this tutorial is the basic knowledge of using the jQuery library.
assuming we have included the jQuery library in our document:
<script type="text/javascript" src="jquery.js"></script>
The next step would be defining our form. For our example, we’ll just use a very simple checkbox list to select which paradigms are applicable to Javascript. We’ll name these checkboxes simply as “paradigm”:
<input type="checkbox" name="paradigm"
value="Imperative">Imperative<br>
<input type="checkbox" name="paradigm"
value="Object-Oriented">Object-Oriented<br>
<input type="checkbox" name="paradigm"
value="Functional">Functional<br>
and of course, we need the “select all” checkbox to perform the operation. We’ll give this checkbox an id name of paradigm_all:
<input type="checkbox" id="paradigm_all">Select All
Now lets go to the main part of jQuery code. What happens when we select the “select all” checkbox is that the checkbox’s status will be passed to all of the checkbox list. For example, if the “select all” checkbox is checked, all checkboxes should also be checked, and vice versa.
So how do we select all of the checkboxes to change their checked state? Fortuantely, jQuery has XPath style selectors which allows us to choose multiple elements in the DOM. the expression:
input[@name=paradigm]
will select ALL input elements that are named paradigm. Here is how the final jQuery script should look like:
$(document).ready(function()
{
$("#paradigm_all").click(function()
{
var checked_status = this.checked;
$("input[@name=paradigm]").each(function()
{
this.checked = checked_status;
});
});
});
If you want to view a demo of the following script or to download the demo source code, just follow the links below.
View Demo
Download Source Code








12 Comments

