Cristian
Cristian

Reputation: 187

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?

Upvotes: 9

Views: 63808

Answers (6)

Stevencxr
Stevencxr

Reputation: 1

$("#divtree").jsTree().get_selected(true)

will return an Array of the "node"

Upvotes: 0

arno
arno

Reputation: 823

Here is how I create a new node in his 'selected' parent:

<div class="input-group mb-3">
    <div class="input-group-prepend">
        <button class="btn btn-secondary" id="add_node">
            Add directory    
        </button>
    </div>
    <input type="text" class="form-control" placeholder="Dir name" id="node_text">
</div>

And my Javascript :

    htmlSource.jstree();

    $('#add_node').on('click', function () {
        let text = $(this).closest('.input-group').find('#node_text').val();
        let selected = htmlSource.jstree('get_selected');
        htmlSource.jstree().create_node(selected, {
            "text": text
        },
        "last",
        function (e) {
            console.log(e);
        });
    })

I hope it can be useful or give someone a lead

Upvotes: 0

Evan Lalo
Evan Lalo

Reputation: 1273

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

console.log(data);

This works for me. Give it a shot!

Upvotes: 13

Maarten Kieft
Maarten Kieft

Reputation: 7125

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)

Upvotes: 7

user3608059
user3608059

Reputation: 41

Try this:

var CurrentNode = $("#divtree").jstree("get_selected");
console.log($('#'+CurrentNode).text());

Upvotes: 3

Murali Mopuru
Murali Mopuru

Reputation: 6570

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());

Upvotes: 18

Related Questions