Cedric Berlanger
Cedric Berlanger

Reputation: 231

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

Upvotes: 13

Views: 17464

Answers (4)

Haider
Haider

Reputation: 1

Here I found a proper way to unselect all nodes:

$("#jstree").jstree().uncheck_all(true);

Upvotes: 0

Ivane Gkomarteli
Ivane Gkomarteli

Reputation: 133

To deselect selected node on click.

$('#my-tree').('click', '.jstree-clicked', function () {
  $('#my-tree').(true).deselect_node(this);
});

Also you can add a listener on deselect.

$("#myTree").on("deselect_node.jstree", function (e, data) {
  ...
});

Upvotes: 0

Hirurg103
Hirurg103

Reputation: 4953

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']
})

Upvotes: 1

fletch
fletch

Reputation: 1641

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.

Upvotes: 11

Related Questions