views:

25

answers:

2

Hello.

I'm using the following snippet to create a select/deselect all checkboxes:

http://www.wiseguysonly.com/2010/01/15/select-and-unselect-all-checkboxes-with-jquery/

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 with variations of the script) that each have a select/deselect checkbox. Currently, checking one effects the entire group of checkboxes.

(UPDATE)

Sorry, here is some example code -

The HTML -

<ul>
    <li class="select-all" ><input type="checkbox" name="select-all" onclick="toggleChecked(this.checked)"> Select / Deselect All</li>
    <li><input class="principal-group" type="checkbox" /> 1</li>
    <li><input class="principal-group" type="checkbox" /> 2</li>
    <li><input class="principal-group" type="checkbox" /> 3</li>
</ul>

<ul>
    <li class="select-all" ><input type="checkbox" name="select-all" onclick="toggleChecked(this.checked)"> Select / Deselect All</li>
    <li><input class="principal-group" type="checkbox" /> 1</li>
    <li><input class="principal-group" type="checkbox" /> 2</li>
    <li><input class="principal-group" type="checkbox" /> 3</li>
</ul>

and the Jquery that currently doesn't differentiate between the two groups of siblings -

function toggleChecked(status) {
$(".principal-group").each( function() {
$(this).attr("checked",status);
})
}

It's phrased differently to your suggestions, as response to a change in status.

A: 

I'm not sure how your HTML is laid out, but if they're in the same container, you can use

$("input[type=checkbox]").click(function() {
   $(this).siblings("input[type=checkbox]").attr("checked", $(this).attr("checked"));
});

Here's a sample.

Marko
A: 

Change your selector accordingly. Lets say if your checkboxes are siblings of a li and when you have an event on li and do the select/unselect, here is the way. You have youu add this code in the scope of a sibling element (li in this case)

$('li').click(function(){
    $(this).siblings().filter('input:checkbox').each( function() {
         $(this).attr("checked",status);
    });
};

Where status can be true or false.

Teja Kantamneni