jsTree select root node on load

4,616 views
Skip to first unread message

Fawad Masood

unread,
May 25, 2015, 9:45:22 AM5/25/15
to jst...@googlegroups.com
i want to select root node 'Root City' when the tree is loaded.


{
"data":"Root City","state":"open","attr":{"id":"47a3e65a-b009-4b13-9985-3c03ad159b4c"}
,"children":[{"data":"City 1","state":"close","attr":{"id":"c2794cd1-0b98-482f-8150-c905dd040729"}
,"children":[]},{"data":"City 2","state":"close","attr":{"id":"cffe9732-51d2-4974-a633-fe0c50e69dcb"}
,"children":[]},{"data":"City 3","state":"close","attr":{"id":"55e18591-5974-442d-bf16-3dc0a5640c4c"}
,"children":[]},{"data":"City 4","state":"close","attr":{"id":"f00c246e-3791-4150-94a0-1c87268befec"}
,"children":[]},{"data":"City 5","state":"close","attr":{"id":"502a8f24-fd7c-4565-87d6-9023a29ada2f"}
,"children":[]}]
}

Ivan Bozhanov

unread,
May 25, 2015, 10:00:23 AM5/25/15
to jst...@googlegroups.com, fawad....@gmail.com
Keep in mind your format is not what jstree understands (you are missing the "text" attribute, and the state attribute should be an object). Maybe you are following v.1 docs? If so - please upgrade to v.3, as v.1 is no longer supported.
To answer your question, you can select the node from the state property:

{"text":"Root City","state": {"opened" : true, "selected" : true },"li_attr":{"id":"47a3e65a-b009-4b13-9985-3c03ad159b4c"}, ...

Best regards,
Ivan

Desmond Daignault

unread,
May 26, 2015, 10:09:52 AM5/26/15
to jst...@googlegroups.com, fawad....@gmail.com
If you need your code to trigger the select handler, this is what I had to do in order to get the event to fire for the initially selected node.

            // trigger on_select for selected node when tree loads
            $jq
("#YOURTREEIDHERE").on("ready.jstree", function(e, data) {
             
var tree = data.instance;
             
var obj = tree.get_selected(true)[0];

             
// trigger the on_select handler for the tree node that is currently selected and ensure that it is opened
             
if (obj) {
               
if (obj.state.opened) {
                  tree
.trigger('select_node', { 'node' : obj, 'selected' : tree._data.core.selected, 'event' : e });
               
} else {
                  tree
.open_node(obj, function() {
                    tree
.trigger('select_node', { 'node' : obj, 'selected' : tree._data.core.selected, 'event' : e });
                 
});
               
}
             
}
           
});

Reply all
Reply to author
Forward
0 new messages