Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the selected Node from a jstree

I am trying to get the selected Node from a jstree.

This is the code in the View

<div id="divtree" >
    <ul id="tree" >
         @foreach (var m in Model.presidentList)
         {
             <li class="jstree-clicked">
                  <a href="#" class="usr">@m.Name</a>
                  @Html.Partial("Childrens", m)
              </li>
         }
     </ul>
</div>

This is the javascript part where I try to retrieve the name of the Node

$(".jstree-clicked").click(function (e) {
        var node = $(this).jstree('get_selected').text();
        alert(node);
});

I have a problem on getting only the selected node. If I select one of the children(last node of the tree for example) I still get the entire list of nodes. Please let me know if you have any idea where I am doing something wrong?

like image 257
Cristian Avatar asked Nov 18 '13 17:11

Cristian


3 Answers

I don't think you should assign class 'jstree-clicked' for each <li> node. And get selected node using jstree container that you used for jstree binding.

console.log($("#divtree").jstree("get_selected").text());
like image 160
Murali Mopuru Avatar answered Nov 19 '22 13:11

Murali Mopuru


var data = $(yourtree).jstree().get_selected(true)[0].text;

console.log(data);

This works for me. Give it a shot!

like image 35
Evan Lalo Avatar answered Nov 19 '22 13:11

Evan Lalo


Since more people found my comment useful I converted it to an answer. Thanks to the answer Murali, I was able to resolve my issue. This code:

$("#divtree").jstree("get_selected",true)

will return the complete object. (Look at the true parameter)

like image 7
Maarten Kieft Avatar answered Nov 19 '22 15:11

Maarten Kieft