How to get the index of selected nodes in jstree

2.2k views Asked by At

I want to use jstree to let the user select nodes and reorder the tree using the drag'n'drop plugin. Here's a jsfiddle demonstrating the current behaviour:

$("#ProductInterests").jstree({
    core: { themes: { icons: false },"check_callback" : true },
    checkbox : { tie_selection : false },
    plugins: ["themes", "checkbox","dnd"]
});

$('button').click(function () {
    alert($("#ProductInterests").jstree(true).get_checked().join(','));
});

http://jsfiddle.net/dt2rk2d1/

At the moment, all selected ids are reported in the order they where selected. Is it possible to get them in the order they appear in the tree? Even after the user drag'n'dropped the items?

1

There are 1 answers

0
vakata On BEST ANSWER

I guess it depends on what you mean by appear in the tree. If you mean visually appear - you can use a generic selector and collect the IDs:

$("#ProductInterests").find('.jstree-checked').closest('.jstree-node')
    .toArray().map(function (v) { return v.id; })

However this will not return nodes that are not visible (which will be a lot since you are using three_state).

If this is not OK for you you can traverse the internal tree model with a recursive function and collect the nodes in their true order regardless if visible or not. To do so, you need to inspect: $("#ProductInterests").jstree(true)._model.data['#'].children

Here is the updated fiddle using the method above (feel free to optimize the function, it is not very elegant):
http://jsfiddle.net/dt2rk2d1/1/