Reputation: 513
My jstree data has the following configuration:
config_collection =
[
{
id: "1"
parent: "#"
text: "First Question"
},
{
id: "1.1"
parent: "1"
text: "First Answer"
},
{
id: "1.2"
parent: "1"
text: "Second Answer"
}
]
And my jstree setup is:
$("#jstree_div").jstree({
'core' : {
'data' : config_collection,
'check_callback' : true,
'multiple' : false
},
'plugins' : [ 'dnd' ]
});
That jstree loads correctly and has all of the basic functionality working, until I get to drag and drop. My actual tree is more complicated, but let's say I want to switch the first and second answer. I can use drag and drop to do that, but when I save and reload none of my changes are preserved. I'm currently trying to code in all of the functionality needed to change the ids of each node affected, but that's getting very hairy very quickly; Aside from coding that functionality in, are there any options to allow me to preserve these changes? Anything built into jstree?
Upvotes: 0
Views: 1697
Reputation: 61
for jsTree simply use
var config_collection = $('#ul_list_id_is_here').jstree(true).get_json('#', {flat:true});
a diffrent aproach if you want to create json from li structure fallow instruction
change your json data as
config_collection =
[
{
id: "1"
parent: "#"
text: "First Question",
li_attr:{
"data-parent" : "#"
}
},
{
id: "1.1"
parent: "1"
text: "First Answer",
li_attr:{
"data-parent" : "1"
}
},
{
id: "1.2"
parent: "1"
text: "Second Answer",
li_attr:{
"data-parent" : "1"
}
}
]
this will add data-parent attribute to li and call buildJson() to create li structure as json
var buildJson = function (root){
if(!root){
root='#ul_list_id_is_here';
}
var result = [];
// get first deepth of li list
$('ol:first > li',root).each(function() {
var itemdata = {};
//if you want to collect all attribute of li tag then use here
// $.each($(this).data(), function(key, value) {
// itemdata[key] = value;
// });
itemdata["id"] = $(this).attr('id');
itemdata["parent"] = $(this).attr('data-parent');
itemdata["text"] = $(this).text();
// check li does have children
if($(this).children("ol").length){
if($(this).find("ol li").length){
itemdata["children"] = buildJson($(this));
}
}
result.push(itemdata);
});
return result;
}
console.log(buildJson());
Upvotes: 1