Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery select/unselect all siblings

I´m trying to select all siblings when first is checked.. and then if it´s unchecked all siblings should be unselected.

but I can´t work it out so any pointers are welcome :)

<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.js'></script>           
    <ul>
    <li><input id="checkall" type="checkbox" />Select all</li>
    <li><input type="checkbox" />Child 1</li>
    <li><input type="checkbox" />Child 2</li>
    <li><input type="checkbox" />Child 3</li>
    <li><input type="checkbox" />Child 4</li>
</ul>

<script type="text/javascript">
            //clicking the first checkbox should check or uncheck all checkboxes in that element 
$(document).ready(function(){
    $('#checkall').click(function(){
        if ($(this).closest('ul').find('input:checkbox').attr('checked', false)) {
            $(this).closest('ul').find('input:checkbox').attr('checked', true)
        }
        else ($(this).closest('ul').find('input:checkbox').attr('checked', true)); {
            $(this).closest('ul').find('input:checkbox').attr('checked', false)
        }
    });
});
</script>
like image 903
Mackelito Avatar asked May 05 '26 23:05

Mackelito


2 Answers

Pretty basic:

    $('#checkall').click(function(){

       //select ul
       $(this).closest('ul')

        //find checkbox
        .find('> li > input[type=checkbox]') //or : input[type=checkbox]

         //not first check - is the 'select all'
        .not(':first')

         //set value
        .prop('checked', this.checked)
    });

Or short:

$('#checkall').click(function(){
   $(this).closest('ul').find('> li > input[type=checkbox]').not(':first').prop('checked', this.checked)
});
like image 155
Kees C. Bakker Avatar answered May 11 '26 17:05

Kees C. Bakker


.attr('checked', false) will set the 'false` value to checked property of the element and not return a boolean value. You can simplify you code like this.

$(document).ready(function(){
    $('#checkall').click(function(){
        $(this).closest('ul').find(':checkbox').attr('checked', this.checked);
    });
});
like image 37
ShankarSangoli Avatar answered May 11 '26 17:05

ShankarSangoli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!