Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deselect selected treenode JStree - jQuery

Situation

When my page is loaded and my treeview is visible, no treenode is selected. When I click on a node, it's selected, which is default behavior.

Question

How can I deselect the node while clicking on the same node? So I want to click on a selected node to deselect it. I have been searching into the documentation. But the event 'select_node' will first select the node before I can check for it's selectstatus.

I know there is a way to deselect a node with code when I click on a button but that's not what I want. I want to click the already selected node.

How can I do this?

Link(s)

Documentation events JStree: http://www.jstree.com/api/#/?q=.jstree%20Event&f=enable_node.jstree

like image 223
Cedric Berlanger Avatar asked Feb 27 '14 14:02

Cedric Berlanger


2 Answers

I've found a way to enable this behavior via adding multiselect plugin. And set multiple configuration option to false when you want single select:

$('#my-tree').jstree({
  core: { multiple: false },
  plugins: ['multiselect']
})
like image 59
Hirurg103 Avatar answered Sep 19 '22 12:09

Hirurg103


This issue popped up for me today. I expected at least a configuration option that could be set when initializing the tree. While it's not pretty, this is what I did to circumvent the issue:

var _selectedNodeId;
$("#myTree").on("select_node.jstree", function (e, _data) {
    if ( _selectedNodeId === _data.node.id ) {
        _data.instance.deselect_node(_data.node);
        _selectedNodeId = "";
    } else {
        _selectedNodeId = _data.node.id;
    }
}).jstree();

Essentially, I am tracking the selected node and checking this against the node that has been clicked. The downside of this method is that if you have a callback firing on "changed.jstree" it will fire twice, since you are "selecting" first and then "deselecting" if it's already selected.

like image 34
fletch Avatar answered Sep 21 '22 12:09

fletch