Search code examples
javascriptjqueryjquery-selectorscheckboxtree

Does jquery checkbox tree support the ability to programatically expand using class selectors instead of Id?


I am using the jquery checkboxtree plugin which works great. I have a situation where I want to programmatically expand certain nodes.

I see that I can do by Id as in the example:

$('#tabs-5-expand').click(function(){ 
    $('#tree5').checkboxTree('expand', $('#tabs-5-node23')); 
 }); 

and I was hoping that I could expand multiple nodes using a class name like this

$('#tabs-5-expand').click(function(){ 
    $('#tree5').checkboxTree('expand', $('.bluetabs')); 
 }); 

but it doesn't seem to do anything. Does anyone know if there is a way to programatically expand or collapse nodes here using class selectors?


Solution

  • Check this fiddle and uncomment the handlers, one at a time. The right way to do it, is to iterate the array of the elements. Check comments for more.

    <ul id="tree6">
        <li><input type="checkbox" checked><label>Root</label>
            <ul>
                <li class="bluetabs"><input type="checkbox"><label>Node 1</label>
                    <ul>
                        <li><input type="checkbox"><label>Node 1.1</label></li>
                    </ul>
                </li>   
                <li><input type="checkbox" checked><label>Node 2</label>
                    <ul>
                        <li><input type="checkbox"><label>Node 2.1</label></li>
                        <li><input type="checkbox"><label>Node 2.2</label></li>
                        <li class="bluetabs"><input type="checkbox"><label>Node 2.3</label>
                            <ul>
                                <li><input type="checkbox"><label>Node 2.3.1</label></li>
                                <li><input type="checkbox"><label>Node 2.3.2</label></li>
                            </ul>
                        </li>   
                        <li><input type="checkbox"><label>Node 2.4</label></li>
                        <li><input type="checkbox"><label>Node 2.5</label></li>
                        <li><input type="checkbox"><label>Node 2.6</label></li>
                    </ul>
                </li>   
            </ul>
        </li>           
    </ul>
    
    <button id="test">Press to expand</button>
    
    
    $('#tree6').checkboxTree({
        initializeChecked: 'expanded',
        initializeUnchecked: 'collapsed'
    }); 
    
    
    //If all the bluetabs are collapsed this will work. If you expand one of the blue ones, then it won't work for the other.
    $('#test').click(function() {
        $('#tree6').checkboxTree( 'expand', $('.bluetabs') );
    });
    
    
    //This will work regardless
    $('#test').click(function() {
        $('.bluetabs').each(function() {
            $('#tree6').checkboxTree( 'expand', $(this) );
        });
    });