user3201640 user3201640 - 6 months ago 39
HTML Question

Checking all immediate child checkboxes onclicking parent checkbox using JQuery

I have a list in my html code where onclick of parent checkbox, the immediate child checkboxes should be checked.

<ul class="test_ex">
<li>
<input type="checkbox" id="chckBox" class="parent" onchange="fnTest(this);" /> <a class="ref" >Fruits</a>
<ul class="example">
<li>
<input type="checkbox" id="chckBox" class="child" /> <a class="ref" > Apple </a>
</li>
<li>
<input type="checkbox" id="chckBox" class="child" /> <a class="ref" > Orange </a>
</li>
</ul>

<ul class="test_ex_sample">
<li>
<input type="checkbox" id="chckBox" class="parent" onchange="fnTest(this);"/> <a class="ref" >Birds</a>
<ul class="example">
<li>
<input type="checkbox" id="chckBox" class="child" /> <a class="ref" > Peacock </a>
</li>
<li>
<input type="checkbox" id="chckBox" class="child" /> <a class="ref" >Parrot </a>
</li>
</ul>
<ul class="example">
<li>
<input type="checkbox" id="chckBox" class="parent" onchange="fnTest(this);"/> <a class="ref" > Food </a>
<ul class="example">
<li>
<input type="checkbox" id="chckBox" class="child" /> <a class="ref" >Bread </a>
</li>
</ul>

</li>
</ul>

</li>
</ul>
</li>
</ul>


I tried many ways to check only the immediate children. But none of them worked.
These are few ways:


  • Tried using .siblings() [Found this solution on stackoverflow only]

    function fnTest(check){

    if($(check).is(':checked')){
    $(check).siblings('.example').find('.child').attr("checked",true);
    }
    else{
    $(check).siblings('.example').find('.child').attr("checked",false);
    }
    }



Fiddle demo 1

Here the first list works properly. Again when clicked on second list it checks the 3rd list children too.


  • Secondly tried this set of code
    Tried using the class which is checked annd getting children from that class. This checks all parents that belong to that class.



Fiddle demo 2

function fnTest(check){


if($(check).is(':checked')){
var classParent = "." + $(check).attr('class');
$(classParent).attr("checked",true);
}
}


It would be great if someone could point out my mistake.

Answer

From your first try of using siblings(). You can change to the following:

function fnTest(check){

    if($(check).is(':checked')){
        $(check).siblings('.example:first').find('.child').prop("checked",true);
    }
    else{
        $(check).siblings('.example:first').find('.child').prop("checked",false);        
    }
      }

By using this it checks only the first children. And also change your .attr to .prop

here is a demo : Fiddle