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

An alternative to PHP's exec function in Node.js

I am interested in developing a piece of software using C (such as prime number factorization) and hosting it on my web server with Node.js. Following that, I would like to create an HTML document containing a form and a button. Upon clicking the button, ...

Issue: Utilized more hooks than in the previous render cycle

After the initial load of a component that renders and makes data calls on the client side, everything works fine. However, when clicking a "see more" button to make another call, an error occurs in the console indicating that there are too many hooks be ...

Sharing data between two Angular 2 component TypeScript files

I'm facing a scenario where I have two components that are not directly related as parent and child, but I need to transfer a value from component A to component B. For example: In src/abc/cde/uij/componentA.ts, there is a variable CustomerId = "sss ...

Troubles with configuring the Express server in relation to the public directory

After creating two separate bundles for my server and client, I encountered an issue where the client bundle is not being downloaded by the browser when accessing the root route. To address this, I instructed Express to treat the public/ folder as a freel ...

Ways to merge values across multiple arrays

There is a method to retrieve all unique properties from an array, demonstrated by the following code: var people = [{ "name": "John", "age": 30 }, { "name": "Anna", "job": true }, { "name": "Peter", "age": 35 }]; var result = []; people. ...

Generate a compilation of products developed with the help of angularjs

I have a request to make a list of items using Directives and share them through controllers. Check out my code example on plunker: Code Example Below is the JavaScript code: var app = angular.module('app', []); app.controller("BrunchesCtrl", ...

I need to transfer the "message" variable from outside to inside the res.json function

Access Control page: https://i.stack.imgur.com/oUSEB.png While working with the 'passport.use' function, I have a message variable that needs to be passed into the 'passport.authenticate' function so it can be utilized in the contro ...

Precise column measurement

I'm currently working on a jQuery project where I need to create a table with columns of exact widths. For example, let's say I want the first column to be exactly 100px wide, including padding (10px on each side). I've tried various combin ...

Display an array containing date objects in a dropdown menu for users to select from

I am working with an API call that returns an array of objects. Each object in the array contains a date or timestamp in ISO format. Right after my render() method, I have the following code snippet: const pickerItems = this.props.currentData.trips.map(t ...

The onClick event handler fails to trigger in React

Original Source: https://gist.github.com/Schachte/a95efbf7be0c4524d1e9ac2d7e12161c An onClick event is attached to a button. It used to work with an old modal but now, with a new modal, it does not trigger. The problematic line seems to be: <button cla ...

event handling for multiple dropdown lists using jQuery and Ajax

I have a situation where I am using two drop down menus to filter some results. When the user changes the option in the first drop down, it should dynamically update the choices in the second one. I managed to replace the options in the second drop down, b ...

What is the process of matching a server response with the appropriate pending AJAX query?

Imagine a scenario where my web app utilizes AJAX to send out query #1, and then quickly follows up with query #2 before receiving a response from the server. At this point, there are two active event handlers eagerly waiting for replies. Now, let's ...

"Unable to retrieve data: API call for JSON information yields no results

Can anyone assist me with fetching an API from a specific URL using create-react-app? My current code is resulting in an empty list that corresponds to the number of fetched arrays. Any suggestions or tips on how to resolve this issue? ... const [error ...

What is the best way to center text vertically within an image?

How can I vertically align a blog entry title on an entry thumbnail image? The image size changes with the window size and the title varies in length for each entry. After finding a website that successfully achieved this effect, I tried replicating it us ...

Transferring information into MySQL through an Android application

I am new to developing a web application for Android and it's my first time experimenting with it. I am encountering an error where a string cannot be converted to a JSONObject. Despite trying everything, I have not been able to find a solution yet. H ...

The tooltip feature for icon buttons within Material UI list items is not functioning properly as anticipated

Just starting out with Material UI and React, I've encountered a strange UI problem that I can't quite figure out. Hopefully someone here can help me identify what I did wrong. My Approach: I have a List in my code where each list item has butto ...

Encountering a problem with vis js events

While constructing a timeline in my vue.js application, I opted to utilize vis.js. Unfortunately, I encountered some issues when attempting to incorporate events. Initially, setting @drop="myDropCallback()" did not trigger the function upon dropping an ite ...

Eliminating the default inline style automatically

My goal is to hide a table row until a radio button is clicked. I attempted using display:none;, but it did not work. Upon inspecting the code in my developer tools, I noticed that the specific table row has a style attribute style="display: table-row; whi ...

The onClick function is failing to work properly, and I need to pass the value of 'cid' based on the result of the button

Is it possible to pass the 'courseid' to local storage when a button is clicked? I am having trouble with onclick not working. How can I retrieve the relevant 'courseid' in the onclick function based on the button clicked? handleClick ...

What is the best way to position a <label> to the left of an <input> field?

Examining the HTML and CSS code below: * { box-sizing: border-box; } .field { overflow: auto; } .field label { float: left; width: 80px; } .field input { display: block; width: 100%; } <div class="field"> <label>Test< ...