Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jstree: create a new child node

Before posting this I've checked other questions on the stackoverflow. one is this:

creating a new node in jstree

But somehow I'm not able to get it working.

I'm fetching the child node details through ajax. When you click on a node it will trigger ajax request and get the child node details. I want to attach these details to the parent(clicked) node in the jstree.

Here is the jsfiddle demo(without ajax): https://jsfiddle.net/8wyqd9om/

Can you please help me with this?

HTML:

<div id='cat_tree'>
<ul>
<li id="1">First
    <ul>

      <li id="2">First</li>
      <li id="3">First</li>
    </ul>
</li>
<li id="4">First</li>
<li id="5">First</li>    
<li id="6">First</li>
</ul>
</div>

js:

$(function () { 
    $('#cat_tree').jstree({"core": {
        "themes":{
        "icons":false
        }
    }}); 

    var data = [
        { "id" : "7", "parent" : "#4", "text" : "second" },
        { "id" : "8", "parent" : "#4", "text" : "second" },
    ];

    $('#click').click(function() {
        $('#cat_tree').jstree().create_node($('#4'), data, 'last', function(){
        alert("done");
        }, true);
    });
});
like image 920
Raghav Avatar asked Feb 06 '16 14:02

Raghav


1 Answers

Please check the below code

$(function() {

  var data = [{
    "id": "p1",
    "parent": "#",
    "text": "Parent-1"
  }, {
    "id": "p2",
    "parent": "#",
    "text": "Parent-2"
  }, {
    "id": "c1",
    "parent": "p2",
    "text": "Child 1"
  }, {
    "id": "c2",
    "parent": "p2",
    "text": "Child 2"
  }, ];


  $("#jstree").jstree({
    "core": {
      "check_callback": true,
      "data": data
    }
  }).on('create_node.jstree', function(e, data) {
    console.log('saved');
  });

  $('#btnCreate').click(function() {

    $('#jstree').jstree().create_node('#', {
      "id": "p3",
      "text": "Parent-3"
    }, "last", function() {
      alert("Parent created");
    });

    $('#jstree').jstree().create_node('p2', {
      "id": "c3",
      "text": "Child 3"
    }, "last", function() {
      alert("Child created");
    });

  });

});

Demo: https://jsfiddle.net/m24fvh39/1/

like image 84
Thangaraja Avatar answered Nov 17 '22 15:11

Thangaraja