Aasim Hussain Khan
Aasim Hussain Khan

Reputation: 1147

How to get data in jstree using variable

This might sound like an amateur question, but i'm stuck at this. I am using jstree, currently I am loading the data for jstree as JSON. I want to convert JSON to a variable. How do I do that?

This is my code:

  var treedata = ['{ "id" : "ajson1", "parent" : "#", "text" : "Customer" }', 
   '{ "id" : "ajson2", "parent" : "ajson1", "text" : "Order number" }',
   '{ "id" : "ajson3", "parent" : "ajson1", "text" : "Date" }',      
   '{ "id" : "ajson4", "parent" : "#", "text" : "Company Name" }',
   '{ "id" : "ajson5", "parent" : "#", "text" : "Contact Name" }',
   '{ "id" : "ajson6", "parent" : "#", "text" : "Name1" }',
   '{ "id" : "ajson7", "parent" : "#", "text" : "Product number1" }'];

  $(function () {
    $('#jstree').jstree({
     "checkbox" : {
      "keep_selected_style" : false
    },
    "core" : {
       // so that create works
       //ACITREE
       "check_callback" : true,
       'data' : treedata
     },

     "types" : {
      "default" : {
        "icon" : "none"
      }},

    "plugins" : [ "checkbox","dnd","sort","types",,"crrm"]

    });
    $('#jstree').on("changed.jstree", function (e, data) {
      console.log(data.selected);
       //document.getElementById("test").innerHTML+=data.selected.text;
    });
    // 8 interact with the tree - either way is OK
    $('button').on('click', function () {
      $('#jstree').jstree(true).select_node('child_node_1');
      $('#jstree').jstree('select_node', 'child_node_1');
      $.jstree.reference('#jstree').select_node('child_node_1');
    });
  });

Please help. Thanks in advance.

Upvotes: 0

Views: 1922

Answers (1)

Kodr.F
Kodr.F

Reputation: 14390

i don't know what you are pointing to exactly but i guess your problem with JSON

here some tips about Json may help you .

  • [] mean JSON Array
  • {} mean json object

the Below code is Json Array you can call the objects from it by loop or by defined the key

var treedata = [{ "id" : "ajson1", "parent" : "#", "text" : "Customer" }, 
                { "id" : "ajson2", "parent" : "ajson1", "text" : "Order number" }];

get object by loop

for(i = 0; i < treedata.length; i += 1) {

    var obj = treedata[i];

     alert(obj.id);
}

get object by define the key

alert(treedata[0].id);

and if you want to convert Json object to string

var string = JSON.stringify(treedata);

convert to Json again

var json = JSON.parse(string);

Hope this information useful

Upvotes: 1

Related Questions