Check boxes clicked all

后端 未结 2 1050
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:46

    Adding the unordered list adds another layer of parent-children. Edit this line:

          $parent = $(this).parent().prevAll(".parent");
    

    to this:

      $parent = $(this).parent().parent().prevAll(".parent");
    

    to correctly point to your intended parent.

    0 讨论(0)
  • 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"

    0 讨论(0)
提交回复
热议问题