samedi 25 janvier 2020

Parent/child checkboxes with label

I'd like to have parent/checkboxes with this behavior :

  1. A click on the parent select/unselect all children
  2. Parent is checked if one or more child is selected
  3. Parent is unchecked if no child is selected

That code works:

<ul class="list-group" id="mydiv">
   <li class="list-group-item"><input type="checkbox" name="parent1" id="parent1" value=""> <label for "parent1">Parent 1</label>
      <ul class="list-group">
         <li class="list-group-item"><input type="checkbox" name="child11" value=""> Child 11</li>
         <li class="list-group-item"><input type="checkbox" name="child12" value=""> Child 12</li>
         <li class="list-group-item"><input type="checkbox" name="child13" value=""> Child 31</li>
      </ul>
   </li>

   <li class="list-group-item"><input type="checkbox" name="parent2" value=""> Parent 2
      <ul class="list-group">
         <li class="list-group-item"><input type="checkbox" name="child21" value=""> Child 21</li>
         <li class="list-group-item"><input type="checkbox" name="child22" value=""> Child 22</li>
      </ul>
   </li>
</ul>

JS:

$('input[type=checkbox]').click(function(){
   $(this).next().find('input[type=checkbox]').prop('checked',this.checked);
   $(this).parents('ul').prev('input[type=checkbox]').prop('checked',function(){
      return $(this).next().find(':checked').length;
   });
});

My concern is that as soon as I set a < label > tag, it doesn't work anymore. I can't figure out why.

Here is Pen : https://codepen.io/Jibeji/pen/povYKXo




Aucun commentaire:

Enregistrer un commentaire