You are here

Example of simple jsTree with conditional select

Submitted by Asif Nowaj, Last Modified on 2019-11-08

jsTree is jquery plugin, that provides interactive trees. jsTree is easily extendable, themable and configurable. One of noticeable feature is its tri-state checkbox. This plugin overrides the activate_node function (the one that gets called when a user tries to select a node) and enables preventing the function invocation by using a callback.

It is demonstrated with a simple example and a funny condition. You can not select a node if the node text contains "2" in it. See below image I can select all other nodes but those having "2" in it.
jsTree With conditional select

Code snippet is below:


<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Simple jsTree with conditional select</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.8/themes/default/style.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.8/jstree.min.js"></script>
    <script type="text/javascript">
        $(function () {

            var jsondata = [
                           { "id": "ajson1", "parent": "#", "text": "Simple root node" },
                           { "id": "ajson2", "parent": "#", "text": "Root node 2" },
                           { "id": "ajson3", "parent": "ajson2", "text": "Child 1" },
                           { "id": "ajson4", "parent": "ajson2", "text": "Child 2" },
            ];

            createJSTree(jsondata);
        });

        function createJSTree(jsondata) {
            $('#SimpleJSTree').jstree({
                "core": {
                    "check_callback": true,
                    'data': jsondata                    
                },
				"conditionalselect" : function (node, event) {
					//funny condition though, just for example, 
					//you can not select those node that has "2" in its text					
					if (node.text.indexOf("2") != -1)					
					{						
						// do not select the node
						return false;
					}
					//select the node
					return true;
				},
                "plugins": ["conditionalselect"]
            });
        }
    </script>
</head>
<body>
    <div id="SimpleJSTree"></div>
</body>
</html>

Discussion or Comment

If you have anything in mind to share, please bring it in the discussion forum here.

https://forum.everyething.com/jstree-f33/