1

My goal is to "prop" the parent checkbox in a nested list. Right now I pull in a directory listing in PHP like this:

function listDirectories($dir, $i, $howDeep) {
            $lastFolder = end(explode("/", $dir));
            $listString .='<li class="closed"><span class="folder"><input type="checkbox" class="userPermissionCheckBox" parent="'.$i.'" howDeep="'.$howDeep.'" value="'.$dir.'" />'.str_replace('_', ' ', $lastFolder).'</span>';
            foreach (glob($dir."/*", GLOB_ONLYDIR) as $d) {
                $howDeep++;
                $listString .='<ul>';
                $listString .=' '.listDirectories($d, $i, $howDeep).' ';
                $listString .='</ul>';
                $i++;
                $howDeep = 1;
            }
            $listString .='</li>';
            return $listString;
        }

That works awesome!, I then bind this jquery/js function to the check boxes to "prop" all of the child boxes when a parent is selected Like This:

 var isAlreadyChecked = $(this).prop('checked');
            $(this).parents(':eq(1)').find('.userPermissionCheckBox').each(function () {
                $(this).prop('checked', isAlreadyChecked);
            });

this also works fantastic.

Where I get stuck is if someone were to check a child box WITHOUT checking the parent box, it will auto check the parent... so i tried something like this:

var isAlreadyChecked = $(this).prop('checked');
             var parentNumber = Number($(this).attr('parent'));
             var howDeepIsNest = Number($(this).attr('howDeep'));
            $(this).parents(':eq(1)').find('.userPermissionCheckBox').each(function () {
                $(this).prop('checked', isAlreadyChecked);
            });
            if(howDeepIsNest > 1){
                var immediateParent = howDeepIsNest - 1;
                $('.userPermissionCheckBox[howDeep='+immediateParent+']').prop('checked', true);
            }

This Kind of works, obviously the auto prop for the child boxes works great, but I can't get auto check for the parent boxes to work. I'm open to any suggestions. Thank you for taking the time to read this.

4

1 回答 1

2

This will:

  • Un/check all children
  • Check all parents
  • Uncheck direct parent if all siblings are also unchecked

Fiddle: http://jsfiddle.net/a7WDk/1/

$('input:checkbox').on('change', function() {
    var $this = $(this),
        $lis = $this.parents('li'),
        $parents = $lis.find('> span > input:checkbox').not(this),
        $children = $lis.eq(0).find('input:checkbox').not(this),
        $related = $lis.eq(0).siblings().find('input:checkbox');

    if($this.is(':checked')) {
        $parents.add($children).attr('checked', 'checked');
    } else {
        if($children.length) {
            $children.removeAttr('checked');
        }

        if($related.length && !$related.is(':checked')) {
            $parents.eq(0).removeAttr('checked').trigger('change');
        }
    }
});
于 2013-08-23T17:41:20.310 回答