Search code examples
javascriptjqueryjstree

JSTree add a new parent or sub child node


we are trying to add a new node using below details :

Here is how my jstree got created :

$('#m_tree_3').jstree({
                      'plugins': ["wholerow", "checkbox", "types"],
                      'core': {
                              "themes" : {
                                      "responsive": true
                              },       
                              'data': $('#m_tree_3').data('treedata'). //--------------->>>>this is a tag where i have my data, i am taking data from here
                      },
                      "types" : {
                              "default" : {
                                      "icon" : "fa fa-folder m--font-warning"
                              },
                              "file" : {
                                      "icon" : "fa fa-file   m--font-warning"
                              }
                      },
              });


$('#m_tree_3').jstree().create_node([null, "New Node", "first", function(){ 
            alert("Dene");
        }, true]);

Here is how it looks in my HTML:

<div id="m_tree_3" class="" data-treedata="{{ json_encode($categories) }}"></div>
<div class="output_value"></div>

I am trying but the node is not getting created.


Solution

  • Two important things to notice here,

    One is that the [ and ] characters in the jsTree documentation are a little bit misleading. They are not describing an array literal, only that all the inputs are optional.

    Further more, it is important to not forget the check_callback parameter in the jsTree core settigns.

    So a fixed code would be:

    $('#m_tree_3').jstree({
         'plugins': ["wholerow", "checkbox", "types"],
         'core': {
              "check_callback": true
              "themes" : {
                  "responsive": true
               },       
               'data': $('#m_tree_3').data('treedata').
         },
         "types" : {
               "default" : {
                   "icon" : "fa fa-folder m--font-warning"
               },
               "file" : {
                  "icon" : "fa fa-file   m--font-warning"
               }
         },  
    });
    

    And for appending the additional parent node:

    $("#m_tree_3").jstree('create_node', null , {"text":"GO somewhere","slug":"hhhhhhhhh","id":2387}, 'last', function() { 
         alert("added"); 
    });