What is the best way to fill in the jquery treeselect widget?

I'm struggling with populating the jquery treeselect widget using a json file or any other method. Since I am new to jquery/javascript, I'm sure I must be missing some basics.

Although I have obtained the plugin from https://github.com/travist/jquery.treeselect.js, I haven't been able to find an example on how to set it up.

<html>
<head>
    <script type='text/javascript' src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.js"></script>
    <script type='text/javascript' src='js/jquery.moreorless.js'></script>
    <script type='text/javascript' src='js/jquery.treeselect.js'></script>
    <script type='text/javascript' src='js/jquery.chosentree.js'></script>

    <link rel='stylesheet' type='text/css' href='css/moreorless.css'/>
    <link rel='stylesheet' type='text/css' href='css/treeselect.css'/>
    <link rel='stylesheet' type='text/css' href='css/chosen.css'/>
    <script type='text/javascript'>
        jQuery(function () {

            var data1 = ["EVENT1", "EVENT2"];
           var data2 = [{
                "id": 1,
                "name": "A green door"
            },
                {
                    "id": 2,
                    "name": "A blue door"
                }
            ]   

            $('div.chosentree').chosentree({
                width: 200,
                deepLoad: true,
                default_value: data2, // not functioning
                load: function (node, callback) {

                    // What should I include here?
                    /**
                     * Typically, this would involve calling jQuery.ajax to fetch a new node
                     * from your server which returns the tree structure for the specified node.
                     */
                }
            });
        });
    </script>
</head>
<body>
<div class="chosentree"></div>
</body>
</html>

Answer №1

If you are curious about how this functions, the best way to understand it is by examining the example files available in the repository located @ https://github.com/travist/jquery.treeselect.js/blob/master/treeselect.html. Within these files, you will come across the following code.

$('div.chosentree').chosentree({
  width: 500,
  deepLoad: true,
  showtree: true,
  load: function(node, callback) {
    setTimeout(function() {
      callback(loadChildren(node, 0));
    }, 1000);
  }
});

The snippet of code inside the load function performs a simulated request to demonstrate what the data might resemble. It achieves this by invoking a method named loadChildren that is outlined in the file accessible at https://github.com/travist/jquery.treeselect.js/blob/master/index.html, which reads as follows...

var maxDepth = 3;
var loadChildren = function(node, level) {
  var hasChildren = node.level < maxDepth;
  for (var i=0; i<8; i++) {
    var id = node.id + (i+1).toString();
    node.children.push({
      id:id,
      title:'Node ' + id,
      has_children:hasChildren,
      level: node.level + 1,
      children:[]
    });
    if (hasChildren && level < 2) {
      loadChildren(node.children[i], (level+1));
    }
  }

  return node;
};

It's crucial to grasp that this process imitates a server request. Essentially, it mimics sending a request to a server and receiving a response structured similarly to the one shown below.

{
  "id": "1",
  "title": "Node 1",
  "has_children": "1",
  "children": [
    {
      "id": "11",
      "title": "Node 11",
      "has_children": "1",
      "children": [

      ]
    },
    ...
    ...
  ]
}

By supplying a single node object to the load function, you can load all the descendants beneath that specific node if desired.

This explanation clears things up. Hope it aids your understanding.

Answer №2

After spending a couple of hours trying to figure out if raw JSON was compatible with my code, I realized that it does work. However, make sure to remember to run your string literal through JSON.parse(jsonString);

For example:

    jQuery(function() {
        JSONObject = JSON.parse('{"id":"01","title":"Node 01","has_children":true,"level":1,"children":[{"id":"011","title":"Node 011","has_children":true,"level":2,"children":[{"id":"0111","title":"Node 0111","has_children":false,"level":3,"children":[]}]}]}');

        $('div.chosentree').chosentree({
            width: 500,
            deepLoad: true,
            load: function(node, callback) {
                    callback(JSONObject);
            }
        });
    });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the power of JavaScript Callback using nano and now.js

every.person.now.guessValue = function(value) { database.find('lists', 'project_names', { startingPoint: value, endingPoint: value + "\u9999" }, function(_, information) { return information.rows.map(function( ...

Using Bloodhound with a JSON generated using Flask's jsonify function is a seamless process

Recently, I have been exploring the Bloodhound typeahead feature to implement database search functionality in my Flask application. I found a helpful guide on how to set this up at: Twiiter Typeahead Custom Templates - Getting Default Example Working $(d ...

Implementing jqGrid in an ASP.NET application with JSON as the data type

I successfully bound the jqgrid using 'data type=local', but now I am looking to bind the jqgrid using JSON datatype. Any assistance would be greatly appreciated. ...

Words hovering in a section next to a captivating picture

I am looking to achieve a specific arrangement: I want two different texts (in block format) to float or display inline next to an image, all within a div element. Despite trying various display settings (such as block and inline for text), I have not be ...

Is it expected to conceal children who are 2 years old?

I came across the following HTML code snippet: <ul id="product_create-header" class="stepy-header"> <li id="product_create-head-0" class="stepy-active"> <div>Categoría</div><span>Categoría</span> </ ...

The default appearance of bootstrap-select appears to be flawed

Utilizing the amazing Bootstrap-select jQuery plugin has brought two unexpected default styles to my selectboxes. Despite inserting the necessary CSS and JS files into my website, all select boxes are displaying with these peculiar default settings (withou ...

Adding various chosen items to a database using ColdFusion

I need help with integrating Coldfusion, jQuery, and Ajax. Can someone guide me on how to insert the selected item from a list into a database? <select name="list" id="list" class="Entry" multiple="multiple"> <cfloop query="#qDta#"> ...

The Angular Google Maps Directive zooms in too much after the "place_changed" event has fired

Currently, I am developing a store locator app for DHL accessible at storefinder.hashfff.com/app/index.html For this project, I decided to utilize the angular-google-maps library for its features. However, in hindsight, working directly with the Google Ma ...

Implementing ExpressJS with MongoDB on a MERN Development Stack

After configuring my ExpressJS & MongoDB client and running Nodemon, I consistently encounter the following warning: "DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the ...

Dealing with CSS specificity issues when incorporating material-ui for React into a WordPress plugin

Struggling to integrate material-ui for react in a wordpress plugin due to conflict with wordpress's styling in forms.css file. Looking for a solution that doesn't require complete restyling of material-ui components to override the default style ...

Challenges with Bootstrap input groups

Despite trying various solutions, nothing seems to be working for me. I attempted using width:200px, but the issue persists. Since my form was quite outdated, I decided to switch to a bootstrap version. However, while others are able to resolve the issue w ...

Having trouble fetching data from a connected Android device to a localhost endpoint using React-Native

I am relatively new to React Native and I am currently working on developing an application. I have a JSON post request that functions correctly on Postman and Expo when accessed through a web browser at http://127.0.0.1:8080. However, when attempting to r ...

Merge two JSON files into a single document

I am currently working on a script that is able to access a JSON file by using the code: $.getJSON( 'alfred.json', function(data) { ... } Recently, I have obtained a second file named alfred_offline.json, which follows the same structure a ...

Place JavaScript buttons within a form element without triggering form submission upon clicking the buttons

Struggling to find the right words, but I'll give it a shot. I have a PHP form with multiple fields, including a textarea where I store some PHP values. I wanted to enhance the appearance of the PHP values by adding a beautifier with CSS styling. Ever ...

Flexbox problem - uneven heights

I have set up a flex box layout and you can view the codepen link here:- https://codepen.io/scottYg55/pen/zYYWbJG. My goal is to make the pink backgrounds in this flexbox 50% of the height, along with the background image so it resembles more of a grid sy ...

Working with deeply nested JSON arrays in Java

I have a JSON file in the format shown below. { "data":[ { "prjId": 1, "name" : "Forj1", "issue": [ { "id": 00001, "status" : "Closed" ...

inSession variable in express: set to false

i keep receiving inSession:false when attempting to log in, it is expected to return true. I am utilizing express session, in combination with postges and sequalize. I have logged the state values and they are being rendered correctly, so they are n ...

``Maybe there is a way to fix the issue of jQuery not functioning properly

I am currently working on integrating jquery with Reactjs to add a class on click event. The functionality works fine when the page is refreshed, but it stops working if I navigate to the page after clicking on any menu item without refreshing. How can I ...

using hover/click functionality with a group of DIV elements

I have a group of DIV elements that I want to apply an effect to when hovering over them with the mouse. Additionally, when one of the DIVs is clicked, it should maintain the hover effect until another DIV is clicked. <div class="items" id="item1"> ...

Fetching the name of a JSON object in JavaScript converted to a string

Is there a way to retrieve the name 'muxEnvironments' as a string from the object? I need it in order to analyze and compare the content type. When I use console.log(obj), the entire object is displayed. My objective is something like this: jso ...