javascriptc#jqueryasp.net-core-mvcjstree

Jstree - only allow to check one node each time in all the Jstree


I have a jstree fill with data and i just want to limit the user to only check one node in all the jstree and when check another uncheck the first and check the other one.

Checkbox property multiple to false not working. My checkbox plugin is configured like this:

    'checkbox': {
        'whole_node': false,
        'tie_selection': false,
        'multiple': false,
        'three_state': false,
        'cascade': 'down'
    },

Thank you.


Solution

  • want to limit the user to only check one node in all the jstree and when check another uncheck the first and check the other one.

    To achieve your above requirement, you can refer to the following code snippet.

    Hide checkbox(es) of root nodes

    <style>
        .jstree li.jstree-open > a.jstree-anchor > i.jstree-checkbox,
        .jstree li.jstree-closed > a.jstree-anchor > i.jstree-checkbox {
            display: none;
        }
    </style>
    

    Html code

    <div id="tree">
        <ul>
            <li id="pnode_1">
                ParentNode 1
                <ul>
                    <li id="child1_1">ChildNode 1</li>
                    <li id="child1_2">ChildNode 2</li>
                </ul>
            </li>
            <li id="pnode_2">
                ParentNode 2
                <ul>
                    <li id="child2_1">ChildNode 1</li>
                    <li id="child2_2">ChildNode 2</li>
                    <li id="child2_3">ChildNode 3</li>
                </ul>
            </li>
           
        </ul>
    </div>
    

    JS code

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
    <script>
        $(function () {
            var Tree = $("#tree").jstree({
                'checkbox': {
                    'whole_node': false,
                    'tie_selection': false,
                    'keep_selected_style': false,
                    'cascade': 'down'
                },
                "plugins": ["checkbox"]
            });
    
            //overwrite default behaviour of check_node function
    
            Tree.on("check_node.jstree", function (e, data) {
                var selectedNodes = $("#tree").jstree().get_checked();
                console.log(selectedNodes);
    
                console.log(data.node.id);
    
                if (selectedNodes.length > 1) {
                    $("#tree").jstree().uncheck_node(selectedNodes[0]);
                }
            });
        });
    </script>
    

    Test Result

    enter image description here