JSFiddle - React, Tailwind, and code Playground

by KARTHIKEYAN K

HTML

<ul id="treeList">
   <li>
   <input type="checkbox" name="selectedRole">
  Root
    <ul>
       <li>
           <input type="checkbox" name="selectedRole">
          Child
       </li>
       <li>
            <input type="checkbox" name="selectedRole">
           Child
             <ul>
               <li>
                   <input type="checkbox" name="selectedRole">
                  Sub child
                </li>
                <li>
                   <input type="checkbox" name="selectedRole">
                     Sub child
                </li>
                   
                 </ul>
              </li>
         
          <li>
            <input type="checkbox" name="selectedRole">
            Child
             <ul>
               <li>
                   <input type="checkbox" name="selectedRole">
                  Sub child
                </li>
                <li>
                   <input type="checkbox" name="selectedRole">
                  Sub child  
                </li>
                   
             
           </ul>
       </li>

</ul>

JavaScript

$('#treeList :checkbox').change(function (){
 $(this).siblings('ul').find(':checkbox').prop('checked', this.checked);
 if (this.checked) {
 $(this).parentsUntil('#treeList', 'ul').siblings(':checkbox').prop('checked', true);
    } else {
        $(this).parentsUntil('#treeList', 'ul').each(function(){
            var $this = $(this);
            var childSelected = $this.find(':checkbox:checked').length;
            if (!childSelected) {
                $this.prev(':checkbox').prop('checked', false);
            }
        });
    }
});