Dan
Dan

Reputation: 23

jsTree Contextmenu get selected node id

Hi I am currently having an issue with the jsTree Context menu. I would like to grab the id of the selected node however I've looked at a number of solutions and none have worked. My code is below.

The function I have which uses tree.get_selected($node) does return an object of the selected node but I'm struggling to access the id parameter of the object. Below I used tree.get_selected($node).id but it says it's undefined but its clearly not when I look at the console.

Can anyone help as to where I'm going wrong?

$("#tree_1").jstree({
    "core" : {
    "themes" : {
        "responsive": false
    },
    // so that create works
    "check_callback" : true,
    'data' : {
        'url' : function (node) {
                if(node.id=='#') {
                    var id = 0; 
                } else {
                    var id = node.id;   
                }
                return 'organisation/getOrganisationLocations/'+id;
            }
        }
    },
    "types" : {
        "default" : {
            "icon" : "fa fa-folder icon-state-warning icon-lg"
        },
        "file" : {
            "icon" : "fa fa-file icon-state-warning icon-lg"
        }
    },
    "state" : { "key" : "demo3" },
    "plugins" : [ "dnd", "state", "types", "contextmenu" ],
    "contextmenu":{         
    "items": function($node) {
            var tree = $("#tree_1").jstree(true);
            return {
                "Create": {
                    "separator_before": false,
                    "separator_after": false,
                    "label": "Create",
                    "action": function (obj) { 
                        $node = tree.create_node($node);
                        tree.edit($node);

                        console.log(tree.get_selected($node).id);
                    }
                },
                "Rename": {
                    "separator_before": false,
                    "separator_after": false,
                    "label": "Rename",
                    "action": function (obj) { 
                        tree.edit($node);
                    }
                },
                "Remove": {
                    "separator_before": false,
                    "separator_after": false,
                    "label": "Remove",
                    "action": function (obj) { 
                        tree.delete_node($node);
                    }
                }
            };
        }
    }
});

Upvotes: 1

Views: 4910

Answers (2)

AlejoE NQN
AlejoE NQN

Reputation: 56

This approach worked for me:

$(node).attr('id')

Upvotes: 4

nawglan
nawglan

Reputation: 11

Declare your id above the jstree declaration (at line 1, put var id;)

Then, in the data.url function, remove var from before each line that assignes to id.

Upvotes: 1

Related Questions