How to preselect nodes using jsTree jQuery plug-in

I am using the jsTree jQuery plugin with its "Checkbox" plugin and using an asynchronous HTTP request to lazily load each level of the tree. Everything works fine, except that I cannot get the tree to pre-select specific nodes after the first level. I use the "selected" attribute to provide an array of IDs for preselection. The identifier at the top level of the tree is correctly selected. However, the identifier at lower levels of the tree is not selected when loading the level. Did I miss something?

Here is the constructor code:

    var myArrayOfIDs = new Array();
    myArrayOfIDs[0] = '123';  //etc...

    $(sDivID).tree(
        {
            data : {
                async : true,
                opts : {url : sURL}
            },
            plugins:{ 
                "checkbox" : {three_state : false}
            },
            selected : myArrayOfIDs,
            ui:{
                theme_name : "checkbox",
                dots : false,
                animation : 400
            },
            callback : {
                beforedata : function(NODE, TREE_OBJ) { return { id : $(NODE).attr("id") || 0, rand : Math.random().toString() } }
            }
        }
    )
+3
source share
3 answers

, .

, , , .. sURL, , , - jsTree onload .

: jsTree jsTree

+2
$(".jstree").jstree({
    "plugins" : [ "themes", "html_data", "checkbox", "ui" ],
    "checkbox": {
        "real_checkboxes": true,
        "real_checkboxes_names": function (n) {
            return [n[0].id, 1];
        },
        "two_state": true
    }
}).bind("loaded.jstree", function (event, data) {
    $('li[selected=true]').each(function () {
        $(this).removeClass('jstree-unchecked').addClass('jstree-checked');
    });
});

jstree.

+6

This is how I update the selection after loading the tree:

$('#jstree_div')
      .on('changed.jstree', treeChanged)
      .on('loaded.jstree', treeLoaded)
      .jstree({
      'plugins': ["checkbox"],
      'core': {
          'data': {
              'url': '/xmldata/getcategories'
          }
      }
  });

function treeLoaded(event, data) {
    data.instance.select_node(['2', '5']); //node ids that you want to check
}
+1
source

Source: https://habr.com/ru/post/1736426/


All Articles