javascriptztree

get Selected Value in JavaScript from ztree


I have a tree which i took sample form zTree but i am unable to get the selected value from this tree. although i have made changes to the original code but here i am posting the original code of official Ztree Demo. Any help!!

<SCRIPT type="text/javascript">
    var setting = {
        data: {
            simpleData: {
                enable: true
            }
        }
    };

Array to Store the Nodes of Tree

    var zNodes =[
        { id:1, pId:0, name:"pNode 1", open:true},
        { id:11, pId:1, name:"pNode 11"},
        { id:111, pId:11, name:"leaf node 111"},
        { id:12, pId:1, name:"pNode 12"},
        { id:121, pId:12, name:"leaf node 121"},
        { id:13, pId:1, name:"pNode 13 - no child", isParent:true},
        { id:2, pId:0, name:"pNode 2"},
        { id:21, pId:2, name:"pNode 21", open:true},
        { id:211, pId:21, name:"leaf node 211"},
        { id:22, pId:2, name:"pNode 22"},
        { id:221, pId:22, name:"leaf node 221"},
        { id:23, pId:2, name:"pNode 23"},
        { id:231, pId:23, name:"leaf node 231"},
        { id:3, pId:0, name:"pNode 3 - no child", isParent:true}
    ];

Tree initialization from that array

    $(document).ready(function(){
        $.fn.zTree.init($("#treeDemo"), setting, zNodes);
    });
</SCRIPT>

Here Tree Displays in Div with id treeDemo. Here i want to alert the selected value in alert box from this tree.

<BODY>
     <div class="content_wrap">
          <div class="zTreeDemoBackground left">
               <ul id="treeDemo" class="ztree"></ul>
          </div>
     </div>
</BODY>

Solution

  • On zTree v3.x, You need two things:

    1) In settings, add a callback

    var setting = {
            ...
            callback: {
                onCheck: zTreeOnCheck
            }
        };
    

    2) ztreeOnCheck in the callback, you get with each check/unchek all selected nodes. Sample

    function zTreeOnCheck(event, treeId, treeNode) {
      var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
      var nodes = treeObj.getCheckedNodes(true);
      console.log(nodes); //Here are all of the selected nodes
    };