jsTree Control with Multiselect – DblClick to toggle, Click to select

As with most things, this turned out to be a hard problem with a simple solution. I was using jsTree to display a product catalog. Originally, I did not implement multiselect. So when a node in the tree was double clicked, it expanded the node. However, when I went to multiselect, double clicking a node expanded it, but also selected it and every child node under it. I needed to decouple those two behaviors.

Double click to expand. Single click on the checkbox to select.

Here is the code in JSFiddle: https://jsfiddle.net/cq9o4t8w/20/

https://jsfiddle.net/cq9o4t8w/20/
Double click to expand the tree. Click checkbox to select nodes. 
</p>
<div id="jstree_div">
  <ul>
    <li id="node_root">root
      <ul>
        <li id="node_1">node 1
          <ul>
            <li id="node_1_1">node 1.1</li>
            <li id="node_1_2">node 1.2</li>
          </ul>
        </li>
        <li id="node_2">node 2</li>
      </ul>
    </li>
  </ul>
</div>
<br />
<b>Selection: </b><span id="selection"></span>
$(document).ready(
  function() {

    $('#jstree_div').jstree({
      plugins: ['checkbox', 'changed'],
    }).on('changed.jstree', function(e, data) {
      var t1 = setTimeout(
        function() {
          var selected_nodes = $('#jstree_div').jstree('get_selected');
          if (Array.isArray(selected_nodes) && selected_nodes.length > 0) {
            // Fire whatever asynchronous process you choose here.
            // Like a call to the server to fetch data. 
            $('#selection').text(selected_nodes.join(', '));
          } else {
            $('#selection').text('');
          }
        }, 500
      )
    })

  })

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s