如果未选中所有子项,则取消选中父项复选框

Uncheck parent checkbox if all child is unchecked

我创建了一个复选框组但未能实现要求。

如果组内的所有复选框都未选中,则顶级复选框应显示为未选中状态。

我对所有选中的复选框所做的操作与我所做的相同。我的第三个 else if 语句不起作用。

我正在尝试满足三个要求:

  1. 如果筛选分组中的复选框未全部选中,则 顶级过滤器在复选框中显示 ( - )。

  2. 如果筛选器分组中的所有复选框都被选中,则 顶级筛选器显示带有复选标记的选定状态。

  3. 如果组内的所有复选框都未选中,则顶级 复选框应显示为未选中状态。

最后一句我没能实现

JS:

 <script>
      $(".faceted-filters").on("click", "#checkAll", function(){

           $(this).parents(".top-lvl-filter").next(".sub-lvl-filter").find("input[type=checkbox]").prop('checked', $(this).prop('checked')); 
           $(this).removeClass("partially-checked"); 

        });

    $("#collapse-one input").change(function(){
        var a = $("#collapse-one input");
        if(a.length !== a.filter(":checked").length){
            $(this).parents(".sub-lvl-filter").prev().find("input").addClass("partially-checked");
        }
        else if(a.length == a.filter(":checked").length){
            $(this).parents(".sub-lvl-filter").prev().find("input").attr('checked','checked');
            $(this).closest(".composite-filter").find(".top-lvl-filter input").removeClass("partially-checked");
        }
        else if(a.length == a.filter.not(":checked").length){
        $(this).closest(".composite-filter").find(".top-lvl-filter input").removeClass("partially-checked");
    }


    });
    </script>

工作示例:http://codepen.io/anon/pen/PqjJdO

你的第一个条件是隐藏第三个条件。

试试这个 -

$("#collapse-one input").change(function(){
    var a = $("#collapse-one input");

  if(a.filter(":checked").length==0){
        $(this).closest(".composite-filter").find(".top-lvl-filter input").removeClass("partially-checked");
  $(this).parents(".sub-lvl-filter").prev().find("input").removeAttr('checked','checked');
  }
    else if(a.length !== a.filter(":checked").length){
        //alert('all checked');
        $(this).parents(".sub-lvl-filter").prev().find("input").addClass("partially-checked");
    }
    else if(a.length == a.filter(":checked").length){
        $(this).parents(".sub-lvl-filter").prev().find("input").attr('checked','checked');
        $(this).closest(".composite-filter").find(".top-lvl-filter input").removeClass("partially-checked");
    }});

以下更改将解决您的问题,

$("#collapse-one input").change(function(){
var a = $("#collapse-one input");
if(a.length > a.filter(":checked").length && a.filter(":checked").length > 0){

    $(this).parents(".sub-lvl-filter").prev().find("input").addClass("partially-checked");
}
else if(a.length == a.filter(":checked").length){
    $(this).parents(".sub-lvl-filter").prev().find("input").prop('checked','checked');
    $(this).closest(".composite-filter").find(".top-lvl-filter input").removeClass("partially-checked");
}
else if(a.filter(":checked").length < 1){

    $(this).closest(".composite-filter").find(".top-lvl-filter input").removeClass("partially-checked");
    $(this).closest(".composite-filter").find(".top-lvl-filter input").prop('checked','');
}


});