Sanjay Rathod Sanjay Rathod - 4 months ago 5
HTML Question

How to check checkbox on change of another checkbox?

i want to check a checkbox when user check checkbox in parent li.

so here is my html code.

<li class="parent3 child2" id="3"><span style="padding-left:60px;"><i aria-hidden="true" class="icon-minus"></i>Civil</span><div>
<label class="viewList"><input type="checkbox" value="49" name="view[]">View</label>
<label class="downList"><input type="checkbox" value="49" name="down[]">Download</label>
<label class="upList"><input type="checkbox" value="49" name="update[]">Update</label>
</div><ul class="submenu" style="display: block;"><li class=" child3" id="4"><span style="padding-left:80px;">test1</span><div>
<label class="viewList"><input type="checkbox" value="60" name="view[]">View</label>
<label class="downList"><input type="checkbox" value="60" name="down[]">Download</label>
<label class="upList"><input type="checkbox" value="60" name="update[]">Update</label>

now i want to check the checkbox of child checkbox.

so i have tried following code.

$('.viewList input').change(function () {
if ($(this).attr("checked")) {
$(this).closest('li').children('.submenu .viewList input').prop( "checked", true );
// not checked

also here is the jsfiddle where also i had tried.

Any help will appreciated. Thanks


You need to use sevral jQuery functions to achieve the same. E.g parents(), find, etc...

Your updated code should look like this.

    $('.viewList input').change(function () {
        if($(this).parents('li').size()>0) {
                var parentLi=$(this).parents('li');
            if(parentLi.find('ul').size()>0) {
                    var childInput=parentLi.find('ul').find('.viewList input');
                } else {

Updated jsFiddle link:

What we need to do here is, when we click on check-box first we will check if there is a LI parent or not, if yes then we will find if there is child UL in it or not. If yes then check/uncheck the corresponding input.