简体   繁体   中英

jQuery traversing parent and children

I have a nested unsorted list and I want to place a click event on the parent checkbox so when it is check it checks all the children checkboxes and vice versa. For some reason I can only get the selector to get all inputs of type check box... ive tried a variety or ways, this is one of them. any suggestions ?

<ul id="parent">
<li>
   <input type='checkbox'>first</input>
   <ul>
      <li><input type='checkbox'>child1</input>
      </li>
      <li><input type='checkbox'>child2</input>
      </li>
   </ul>
</li>

<li>
   <input type='checkbox'>second</input>
   <ul>
      <li><input type='checkbox'>child1</input>
      </li>
      <li><input type='checkbox'>child2</input>
      </li>
   </ul>
</li>

</ul>

jQuery

   $('#parent > li input[type=checkbox]').click(function() {

            var parent = $(this);

            if ($(parent).is(':checked')) {
                $('li > input[type=checkbox]', parent).each(function() {
                    $(this).attr('checked', true);
                });
            }
            else {
                $('li > input[type=checkbox]', parent).each(function() {
                    $(this).attr('checked', false);
                });
            }
        });

This should work:

First you go back to the LI and than you search for the checkboxes

$('#parent > li input[type=checkbox]').click(function() {

    $(this).closest("li").find("ul li input[type=checkbox]").attr('checked', $(this).is(':checked'))

});

However you might consider adding some class names. So your code becomes more readable.

<li>
   <input type='checkbox' class='category'>first</input>
   <ul>
      <li><input type='checkbox' class='subcategory'>child1</input>
      </li>
      <li><input type='checkbox' class='subcategory'>child2</input>
      </li>
   </ul>
</li>

Than your jQuery would look like this:

$("#parent .category").click(function(){

    $(this).closest("li").find(".subcategory").attr('checked', $(this).is(':checked'))

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM