0

I have a buildTree(); function that builds checkboxes in LIs within nested ULs. The outermost UL is wrapped inside div#tree.

HTML

<div id="tree">
    <ul>
        <li class="speed parent-list">
            <input type="checkbox" name="speed" id="speed">speed<span class="glyphicon glyphicon-chevron-up"></span>
            <ul class="speed" style="display: block;">
            <li class="hor_speed"><input type="checkbox" name="hor_speed" id="hor_speed">hor_speed</li>
            <li class="ver_speed"><input type="checkbox" name="ver_speed" id="ver_speed">ver_speed</li>
            <li class="heading"><input type="checkbox" name="heading" id="heading">heading</li>
            </ul>
        </li>
        <li class="health"><input type="checkbox" name="heading" id="heading">health</li>
        <li class="battery_level"><input type="checkbox" name="heading" id="heading">battery_level</li>
    </ul>
</div>

I want all other checkboxes to be disabled once any two checkboxes inside the tree are checked. I have done this much so far but it does not work.

JS

buildTree();

var checkboxes = $('#tree [type=checkbox]');

checkboxes.change(function(){
  if(checkboxes.filter(':checked').length === 2){
   checkboxes.filter(':not(:checked)').prop('disabled',true);
  }
  else {
   checkboxes.prop('disabled',false);
  }
});

UPDATE The code works perfect if I place the rendered tree in the HTML file directly but once it it rendered using jquery, it does not work.

Nishan Hitang
  • 855
  • 3
  • 10
  • 36

1 Answers1

1

Looks like you are loading the content dynamically, you need event delegation to attach the event to dynamically added DOM. Something like this:

 $('#tree').on('change','[type=checkbox]',function(){
 if($('#tree [type=checkbox]').filter(':checked').length === 2){
   $('#tree [type=checkbox]').filter(':not(:checked)').prop('disabled',true);
 }
 else {
   $('#tree [type=checkbox]').prop('disabled',false);
 }});
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125