I have page, where user can create a document and one of the inputs is JsTree input, where on click opens a modal and new JsTree generates by JSON data every time. After user select some of the options, they submit it and text from selected nodes displays in input, also selected nodes themselves are saved in another hidden input.
Problem is, whenever user wants to change selected nodes, they need to open all the subnodes again, manually. I succeed only at making previously selected 1st level nodes be opened, after user selected it and opened JsTree again.
The problem is also, it takes some time for JsTree to generate subnodes, after parent node opening. So when my code opened node "2", it wants to open "2.2", but it doesn't exist at this moment. I tried to manually set setTimeout between opening every node, but it doesn't help.
My question is, how to open and select previously selected subnodes (for example 3.1.1.1) in just generated JSON JsTree
$("#container-test").on("ready.jstree", function() {
if(selectedNodes && selectedNodes.length > 0) {
selectedNodes.forEach(async function(node) {
if(node.parents.length >= 2) {
var allParents = node.parents.reverse()
for(i = 1; i < allParents.length; i ) {
nodesOpener(allParents[i])
}
}
})
}
})
function nodesOpener(parent) {
$("#container-test").jstree("open_node", $("#" parent))
setTimeout(function() {
}, 1000)
}
CodePudding user response:
The open_node
method accepts a callback to call after node opened. If that doesn't work with your data fetching mechanism, maybe you should use another event.
Here's an example:
// after_open
var elem = $('#jstree_demo')
elem.jstree({
'core': {
'data': [{
"id": "ajson1",
"parent": "#",
"text": "Simple root node"
},
{
"id": "ajson2",
"parent": "#",
"text": "Root node 2"
},
{
"id": "ajson3",
"parent": "ajson2",
"text": "Child 1"
},
{
"id": "ajson4",
"parent": "ajson2",
"text": "Child 2"
},
{
"id": "ajson5",
"parent": "ajson4",
"text": "Child 2.2"
},
]
}
});
function open(id_list) {
while (id_list.length) {
var id = id_list.shift();
elem.jstree('open_node', id, function() {
open(id_list);
});
}
}
elem.on("ready.jstree", function() {
open(['ajson2', 'ajson4']);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.12/jstree.min.js" integrity="sha512-TGClBy3S4qrWJtzel4qMtXsmM0Y9cap6QwRm3zo1MpVjvIURa90YYz5weeh6nvDGKZf/x3hrl1zzHW/uygftKg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.12/themes/default/style.min.css" integrity="sha512-pg7xGkuHzhrV2jAMJvQsTV30au1VGlnxVN4sgmG8Yv0dxGR71B21QeHGLMvYod4AaygAzz87swLEZURw7VND2A==" crossorigin="anonymous" referrerpolicy="no-referrer"/>
<div id="jstree_demo"></div>