Jquery Jstree checkbox events capture

user529011 picture user529011 · Jan 28, 2011 · Viewed 16.6k times · Source

I am totally new to jQuery and jstree. I am using jstree and populating the data using xml. But would like to capture event for each node whether checked or not along with their Ids. I tried using jstree's plugins API like change_state(),check_node() or select_node() but it's not working. Also I would like to get all selected nodes data in an array for further processing..Can anyone help?

Thanks...

Answer

Toadmyster picture Toadmyster · Mar 31, 2011

I like the jstree plugin but it's not well documented, nor is it built to conform to say, jquery ui standards of plugin development. I have used 1.0rc2 to accomplish what you're trying to do.

You have to bind the "loaded" event before you instantiate the jstree so I'm guessing it's the same with the "change_state" event. The other thing to watch out for is that "change_state" is more than just a change due to a check box. For instance it will also fire when you expand a node (but not collapse, for some reason). That said, I do some kludgey checking in the "change_state" handler to try and filter out unwanted events from the checkbox change. The minimum code for tapping the handler is

$("#treeElement").bind("change_state.jstree", function (e, d) {
    var tagName = d.args[0].tagName;
    var refreshing = d.inst.data.core.refreshing;
    if ((tagName == "A" || tagName == "INS") &&
      (refreshing != true && refreshing != "undefined")) {
    //if a checkbox or it's text was clicked, 
    //and this is not due to a refresh or initial load, run this code . . .
    }
});

Your clicked element is then d.rslt and you can get checked items with d.inst.get_checked() for just the element clicked, or d.inst.get_checked(d.rslt) for an object containing the sub nodes that are checked. Use jquery's .each function to process the nodes.