jstreejstree-search

JS Tree - Select parent node when all the child nodes are selected


I am using JSTree. When you check a node, I want to see if its all sibling nodes are also selected, if yes, I want to select the parent node and deselect all the child nodes. How can I achieve this with JsTree?


Solution

  • You may need to tweak it to fit your situation but this should be basically what you need:

    $(jsTreeSelector).on("select_node.jstree", function (node, selected) {
        var parentNode = $(jsTreeSelector).jstree(true).get_parent(selected.node.id);
        var siblingNodes = $(jsTreeSelector).jstree(true).get_children_dom(parentNode);
        var allChecked = true;
        $(siblingNodes).each(function () {
            if (!$(this).children('.jstree-anchor').hasClass('jstree-clicked')) allChecked = false;
        });
        if (allChecked) {
            $(siblingNodes).each(function () {
                $(jsTreeSelector).jstree(true).deselect_node(this);
            });
            $(jsTreeSelector).jstree(true).select_node(parentNode);
        }
    });
    

    Make sure three_state is set to false in your tree config