views:

32

answers:

3

How can I use a parent checkbox to check and un-check all child checkboxes.

E.g.

Checkbox ID               = 1
Child Checkbox ID         = 1-1
Child Checkbox ID             = 1-2
Grand-child Checkbox ID       = 1-2-1
Grand-child Checkbox ID       = 1-2-2

The code I've written so far uses the hat character ^ to check all checkboxes beginning with the ID of the selected checkbox, so for instance; Clicking 1 will attempt to check all boxes with an ID beginning with 1-. Checking 1-2 will check all checkboxes beginning with 1-2.

$("input[type='checkbox']").live('click', function() {
    var selected = $(this).attr('id').match(/\d+$/);
    alert(selected);
    $("input[id^='buCheck_"+selected+"-']").attr('checked','checked');
});
A: 

Try this one

Demo

rahul
This works for a master parent of all checkboxes but what if there are child boxes with sub-children. For example, a child should only check the children of itself not all boxes.
A: 

How about this one?

http://jsfiddle.net/wfMXv/2/

Joachim Pileborg
Yes this looks great. One concern I have though, the .each on :checkboxes, this I'm assuming will loop through every checkbox on the page? My worry here is that I have potentially hundreds of boxes and performance concerns.
Use $(":checkbox[class^='" + top_name + "']") as selector for the each call, then you don't need the inner if-statement. See http://jsfiddle.net/wfMXv/4/.
Joachim Pileborg
A: 

You didn't really explain what your problem is. I'm guessing it doesn't work for the sub-checkboxes.

It's probably easiest to just drop the parsing of the id:

$("input[type='checkbox']").live('click', function() {
    var selected = $(this).attr('id');
    alert(selected);
    $("input[id^='"+selected+"-']").attr('checked','checked');
});
RoToRa