Jquery Check parent checkboxes in nested ul li

后端 未结 5 1957
情话喂你
情话喂你 2021-01-02 12:48

I have a script that will check and uncheck all children checkboxes in a nested list. I am now trying to get it so I can check a low level checkbox and it will check all the

5条回答
  •  失恋的感觉
    2021-01-02 13:01

    It looks like you want something like this

    $('input[type=checkbox]').click(function(){
        if(this.checked){ // if checked - check all parent checkboxes
            $(this).parents('li').children('input[type=checkbox]').prop('checked',true);
        }
        // children checkboxes depend on current checkbox
        $(this).parent().find('input[type=checkbox]').prop('checked',this.checked); 
    });
    

    FIDDLE

    If you want to check up and down hierarchy - you can do it like this

    $('input[type=checkbox]').click(function(){
        // children checkboxes depend on current checkbox
        $(this).next().find('input[type=checkbox]').prop('checked',this.checked);
        // go up the hierarchy - and check/uncheck depending on number of children checked/unchecked
        $(this).parents('ul').prev('input[type=checkbox]').prop('checked',function(){
            return $(this).next().find(':checked').length;
        });
    });
    

    FIDDLE

提交回复
热议问题