Search code examples
jstree

How to get selected node's text in jstree


I have a jstree like shown below

enter image description here

and have the code in my script

$("#jstree").click(function (e) {
    var node = $("#jstree").jstree('get_selected');
    $('#resultText').html(node);
});

What i need is if i am selecting book, title, price i need to display output as book-title-price. By using above code i can get ids ie. 1-1_1-1_2 of my selected nodes but how can i get texts of the selected nodes in the above format?

COMPLETE CODE for jstree integration.

@model List<XMLNodeSearch.Models.NodeSearchModel>
<link href="~/vakata-jstree-8ea6ce7/dist/themes/default/style.min.css"     rel="stylesheet" />
<script src="~/Script/jquery-1.12.0.min.js"></script>
<script src="~/vakata-jstree-8ea6ce7/dist/jstree.min.js"></script>
<script src="~/vakata-jstree-8ea6ce7/dist/jstree.js"></script>

<script>
   $(function () {
   $('#jstree').jstree();
   $("#jstree").click(function (e) {
   var node = $("#jstree").jstree('get_selected').text();//This line with text() will throw an error
   $('#resultText').html(node);
  });
</script>

<section>
<label>Result - <span id="resultText"></span></label>
<div id="NodeResult">
    @if (Model != null)
    { 
        <div id="jstree">
            @foreach (var treeNode in Model)
            {
                <!-- in this example the tree is populated from inline HTML -->
                <ul>
                    <li id="@treeNode.Id">@treeNode.NodeName
                        @if(treeNode.ChildNode.Count() > 0)
                        {
                            <ul>
                                @foreach (var childNd in treeNode.ChildNode)
                                {
                                    <li id="@childNd.Id">@childNd.NodeName</li>
                                }
                            </ul>
                        }
                    </li>
                </ul>
            }
        </div>
    }
</div>
</section>

Solution

  • Finally found the solution to my problem. I am posting the answer here for anyone's future reference.

    What i did is added the following script in my script block.

        $('#jstree').on('changed.jstree', function (e, data) {
            var i, j, r = [];
            for (i = 0, j = data.selected.length; i < j; i++) {
                r.push(data.instance.get_node(data.selected[i]).text);
            }
            $('#resultText').html('Selected: ' + r.join(', '));
        }).jstree();
    

    This given me the desired output.