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);
})
Have fun!
Worked a treat, thanks Tim.
This is a great help, but just wondering how you might go about localising the effected checkboxes to only those that are siblings (i.e. in the same group of li items) of the select/deselect box.
I have multiple lists of checkboxes being generated dynamically (so difficult to give them different selector classes to target wirth variations of the script) that each have a select/deselct checkbox. Currently cehcking one effects all the groups of checkboxes.
Thanks.
Why bother with a loop? You can simply call directly:
$(“.checkbox”).attr(“checked”,status);
Found this and it worked nicely. Thank you for writing so clearly. I was daunted by the scope and length of other articles on a similar task. Simply done. Thanks very much.
Why not just use $(‘:checkbox’) ?
It will select all checkboxes in a document. Saves having to put classes on it to identify them.
http://api.jquery.com/checkbox-selector/
@Dylan sure – but what if you have other checkboxes on the page?
A simple example how to check and uncheck.
$(document).ready(function(){
$(‘#checkall’).click(function(){
var status = $(this).attr(“checked”);
$(“.checkBox”).attr(“checked”,status);
});
});
});