Check boxes clicked all

后端 未结 2 1049
Happy的楠姐
Happy的楠姐 2021-01-26 05:19

I want to select the parent item when any of the child is clicked. This code is working checked and check.

$(function() {
  $(\".child\").on(\"click\",function(         


        
2条回答
  •  长发绾君心
    2021-01-26 05:47

    after looking at your code, i have come up with a solution that i think you're going for.

    by using custom attributes, i selected the top level checkbox if one of the child checkboxes is selected. if at least one child level checkbox is checked, the parent level stays checked. otherwise, unchecked. this is probably easier than navigating the DOM and ended up being much less code.

    $(function() {
      $(".child").change(function() {
          if ($('.child[thisparent=' + $(this).attr('thisparent') + ']:checked').length == 0) {
              $('#' + $(this).attr('thisparent')).prop('checked', false);
          }
          else {
              $('#' + $(this).attr('thisparent')).prop('checked', true);
          }
      });
      $(".parent").change(function() {
          $('input[thisparent="' + $(this).attr('id') + '"]').prop('checked', $(this).prop('checked'));
      });
    });
    

    JSFiddle: here

    also, your html is invalid. your "il" tags should be "li"

提交回复
热议问题