A
A
Alexey2015-11-01 01:03:42
JavaScript
Alexey, 2015-11-01 01:03:42

How to mark elements in parent?

Hello. I have some code like this:

<li class="close">
   <input type="checkbox" id="check_2" name="tags[]"> <label for="check_2">Первый чакбокс</label>
   <ul>
      <li>
          <input type="checkbox" id="check_118" name="tags[]"> <label for="check_118">Второй чекбокс</label>
          <ul>
               <li>
                    <input type="checkbox" id="check_119" name="tags[]"> <label for="check_119">Третий чекбокс</label>
                </li>
          </ul>
      </li>
   </ul>
</li>


How can I make sure that if the third checkbox is checked, then all parent (first and second) checkboxes are also checked? And if the second one is marked, then only the first one will be marked with it. Moreover, nesting can be any.
I tried recursion, but my browser freezes...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Immortal_pony, 2015-11-01
@dzheka3d

.parents() will help you find the parent elements for each checkbox.
.children() will help you find checkboxes in parent elements.
Example (parent checkboxes will have the same value as the selected one):

(function($) {
  $('input[type="checkbox"]').on('change', function() {
        var isChecked = $(this).prop('checked');
            
    	$(this).parents().children('input[type="checkbox"]')
            .prop('checked', isChecked);
    })    
})(jQuery);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question