Question

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);
Was it helpful?

Solution 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).

OTHER TIPS

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.

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
            });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top