Nikhil
Nikhil

Reputation: 1186

JSTree check is selected nodes are leaf or make only leaves selectable

I created a jstree as follows

$('#js-tree').jstree({
            'core' : {
              'data' : {
                'url' : "${pageContext.request.contextPath}/makeTree",
                "plugins" : [ "types", "search"],
                'data' : function (node) {
                  return { 'id' : node.id };
                }
              }
            }
            });

I want to check if a selected node is a leaf node while submitting the information -

var selectedLeaves = $("#js-tree").jstree("get_selected");

But this gives me array of id's only. How do I either use is_leaf method to filter our only leaf nodes from the selected nodes? I referred to this post - Force user to select only leaf nodes This solution did not work for me.

Upvotes: 3

Views: 3633

Answers (2)

Mir Gulam Sarwar
Mir Gulam Sarwar

Reputation: 2648

Here is what worked for me

var res = jQuery.jstree.reference('#js-tree').get_json('#', { flat: true });
                var cnt = 0;
                for (var i = 0, j = res.length; i < j; i++) {
                    if (res[i].parent !== '#') {
                        cnt++;
                    }
                }

cnt is the ourput

Upvotes: 0

Nikhil
Nikhil

Reputation: 1186

I found a solution on my own using an argument to the get_selected api to filter out the leaves from the folders -

var nodes = $("#js-tree").jstree(true).get_selected("full", true);
$.each(nodes,function(i, node){
  if(node.children.length >0){
    console.log("not leaf");
  }
  else{
    console.log("leaf");
  }  
});

If you have a better solution please let me know.

Upvotes: 5

Related Questions