How can I get the id of the selected node in a jsTree?
function createNewNode() {
alert(\'test\');
var tree = $.tree.reference(\"#basic_html\");
select
Unable to get harpo's solution to work, and unwilling to use Olivier's solution as it uses internal jsTree functions, I came up with a different approach.
$('#tree').jstree('get_selected').attr('id')
It's that simple. The get_selected
function returns an array of selected list items. If you do .attr
on that array, jQuery will look at the first item in the list. If you need IDs of multiple selections, then treat it as an array instead.
In the most recent version of jsTree (checked at 3.3.3), you can do this to get an array of IDs:
var ids = $('#tree').jstree('get_selected');
This will return, for example, ["selected_id1", "selected_id2", "selected_id3"]
. If you want to get the selected nodes (not IDs), you can do this:
var nodes = $('#tree').jstree('get_selected', true);
The current docs contain more information.
I was having problems getting the selected ids from a tree with MULTIPLE selections. This is the way I got them:
var checked_ids = [];
$("#your-tree-id").jstree('get_selected').each(function(){
checked_ids.push($(this).data('id'));
});
In my case, the data call doesnt work. I succeed in accessing my node data by using attr function.
$("#tree").jstree("get_selected").attr("my-data-name");
You can use the following code var nodes = $("#jstree_demo_div").jstree(true).get_selected("full", true);//List of selected node
nodes[0].id//Which will give id of 1st object from array
to get all selected ids use the below code
var selectedData = [];
var selectedIndexes;
selectedIndexes = $("#jstree").jstree("get_selected", true);
jQuery.each(selectedIndexes, function (index, value) {
selectedData.push(selectedIndexes[index].id);
});
now you have all the selected id's in the "selectedData" variable