Search code examples
javascripthtmltreedropdown

Show a tree structure in dropdown html


I am making my code changes below and would like to show my tree structure in the form of a dropdown

https://jsfiddle.net/sjmcpherso/kc9fehyz/

enter image description here

var vDOM = document.createDocumentFragment(); //Create a Document Fragment to store your Virtual DOM
function formCategoryTrees(object,par) { //Use the parent node as a parameter to create hierarchy
   var ul = document.createElement('ul');
   _.each(object,function(objectValues ){       
        var li = document.createElement('li');
        var leafCategoryId = objectValues["id"];
        var leafCategoryName =  objectValues["name"]; 
        li.appendChild(document.createTextNode(leafCategoryName + " " + leafCategoryId));

        if(objectValues["children"]) {      
                formCategoryTrees(objectValues["children"],li);
        }
        ul.appendChild(li);

    })    
    par.appendChild(ul);  //Append to the parent node after each iteration
}
formCategoryTrees(object.records,vDOM);
document.body.appendChild(vDOM); //Append your Virtual DOM to your page

Solution

  • Use the jsTree plugin of jQuery.

    Here a demo.

    You have to write something like:

    $('#jstree_demo').jstree({
      "core" : {
        "animation" : 0,
        "check_callback" : true,
        "themes" : { "stripes" : true },
        'data' : {
          'url' : function (node) {
            return node.id === '#' ?
              'ajax_demo_roots.json' : 'ajax_demo_children.json';
          },
          'data' : function (node) {
            return { 'id' : node.id };
          }
        }
      },
      "types" : {
        "#" : {
          "max_children" : 1,
          "max_depth" : 4,
          "valid_children" : ["root"]
        },
        "root" : {
          "icon" : "/static/3.2.1/assets/images/tree_icon.png",
          "valid_children" : ["default"]
        },
        "default" : {
          "valid_children" : ["default","file"]
        },
        "file" : {
          "icon" : "glyphicon glyphicon-file",
          "valid_children" : []
        }
      },
      "plugins" : [
        "contextmenu", "dnd", "search",
        "state", "types", "wholerow"
      ]
    });
    

    If give us more details, I can help you better.