Check boxes clicked all

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() {
      $parent = $(this).prevAll(".parent");
      if ($(this).is(":checked")) $parent.prop("checked",true);
      else {
         var len = $(this).parent().find(".child:checked").length;
         $parent.prop("checked",len>0);
      }    
  });
  $(".parent").on("click",function() {
      $(this).parent().find(".child").prop("checked",this.checked);
  });
});

It's working with inputs (See this link)

<input type='checkbox' name='cat' class='parent' value='cat1' />Category 1<br>
<input type='checkbox' name='foo' class='child' value='1' />SubCategory 1<br>
<input type='checkbox' name='foo' class='child' value='1' />SubCategory 2

But with < li > check is not working (See this link)

<input type='checkbox' name='cat' class='parent' value='cat1' />Category 1
<ul>
    <il><input type='checkbox' name='foo' class='child' value='1' />SubCategory 1</il>
    <il><input type='checkbox' name='foo' class='child' value='1' />SubCategory 2</il>
</ul>    

Answers:

Answer

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"

Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.