ow to set a group of checkboxes to checked or unchecked usin

ow to set a group of checkboxes to checked or unchecked usin

Postby tomrff » Thu Apr 28, 2011 1:57 pm

This post explains how to set a group of checkboxes to checked or unchecked using jQuery 1.3, by clicking an “All” or “None” button.

First, let’s select our group of checkboxes. I’ve seen some fairly complicated jQuery selectors for finding checkboxes on a page, but it seems to me the easiest thing to do is just assign a common class to each one in a group, even if you don’t define the class in your stylesheets. Like this:

<input type="checkbox" class="selsts" name="selsts" value="E"> Emailed
<input type="checkbox" class="selsts" name="selsts" value="W"> Work in Progress
<input type="checkbox" class="selsts" name="selsts" value="P"> Pending client call
<input type="checkbox" class="selsts" name="selsts" value="R">R-Returned call

the jQuery selector for this is: $(".selsts") .

We could also select all the elements based on their common name, which I think goes like this: $(['name=selsts']) .
But I prefer classes, because you can easily change their names without affecting server-side code that may be dependent on form field names.

Let’s say we have two buttons on our page, using the following markup:

Select: <input type="button" id="allsts" value="All">, <input type="button" id="nosts" value="None">

To make all our checkboxes checked:

$("#allsts").click(function() {
$(".selsts").attr('checked', true);
});

To uncheck all the checkboxes:

$("#nosts").click(function() {
$(".selsts").attr('checked', false);
});

That’s it.

To determine if a checkbox is checked or not, we can loop through the array like this:

$('.selsts' ).each( function() {
var isitchecked = this.checked;
});

Or, individually:

if ($('#somecheckbox').checked == true) { blah blah ... }
tomrff
 
Posts: 33
Joined: Sat Jan 08, 2011 10:12 pm

Return to JQuery

Who is online

Users browsing this forum: No registered users and 1 guest

cron