Get checked nodes in a jsTree

半世苍凉 提交于 2019-12-20 02:27:56

问题


I have a working JSTree based on JSON data, and the checkbox plugin displays boxes next to each item -- so far so good. Now I want to get which nodes the user has checked, so I can do something with the data.

Unfortunately I haven't found a way to do it through the documentation or web searches. A few answers on SO say to use a get_checked method, but either I'm really missing something or my version of JSTree doesn't have that (i.e. that string doesn't appear anywhere in the project files). I'm on version 3.0.0, which is the latest right now.

Could someone please point me either to a) how to get the checked items, or b) how to access some iterable representation of the tree so I can grab them myself?

(I should mention I'm pretty new to Javascript.)

Here is how I set up the tree, which is based on the documentation on the website:

var treeInit = { core: { data : [
       /* all my data */
    ] 
}};
treeInit.plugins = ["checkbox"];
$('tree_div').jstree(treeInit);

回答1:


I have also faced the same problem with jstree version 3.0.0 . I found a simple solution after hours of surfing. Hope it help others.

var result = $('#your_tree').jstree('get_selected'); 

This line returns an array of selected values.




回答2:


I found an answer. By calling $('#tree').jstree('get_json'), you can get a JSON representation of the whole tree. From there it's pretty straight forward to recurse through the tree nodes and grab all the checked ones. Again, this is for version 3.0.0 (since it seems that the API has changed a lot across versions).




回答3:


Using 3.3.8 version of jsTree, my prefered way of getting it as below using get_selected: Please remember, it only counts those nodes that are selected, it won't count any indeterminate nodes. For complete and working sample code, you can have view https://everyething.com/Example-of-jsTree-to-get-all-checked-nodes

$('.btnGetCheckedItem').click(function(){
                var checked_ids = []; 
                var selectedNodes = $('#SimpleJSTree').jstree("get_selected", true);
                $.each(selectedNodes, function() {
                    checked_ids.push(this.id);
                });
                // You can assign checked_ids to a hidden field of a form before submitting to the server
            });


来源:https://stackoverflow.com/questions/21322069/get-checked-nodes-in-a-jstree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!