Develop a Treeview using the selection of lists using the 'li' element and Json information

I need assistance in creating a tree view using a list of items in ul li and JSON data. The tree view hierarchy should show the selected list item at the first level, followed by corresponding values from the JSON data at the next level. Please guide me on how to achieve this.

I have included an OUTPUT example of a treeview with selected li items along with my data.

JSON DATA The format will be similar for all list elements

data={
  project_name: 'Sales1',
  info: {
    Value1: 'Value1',
    Value2: 'Value2'
   }
}

$(document).ready(function() {
  $('#projects-menu').append("<li  value='sales1'>Sales 1</li>")
 

  $(document).on('click', '#projects-menu > li', function(event) {
    event.preventDefault();
    if (event.ctrlKey) {
      if ($(this).hasClass('selected')) {
        $(this).removeClass('selected');
      } else {
        $(this).addClass("selected");
      }
    } else {
      $("#projects-menu > li").removeClass("selected");
      $(this).addClass("selected");
    }
  });

})
ul.menu {
  margin-top: 30px;
  list-style-type: none;
}

ul.menu li {
  background-color: #e0e0e0;
  padding: 8px 12px;
  border: solid 2px white;
  cursor: pointer;
  border: 3px solid #FFFFFF;
  border-radius: 10px;
}

ul.menu li:hover {
  background-color: #A9A9A9;
}

ul.menu li.selected {
  background-color: #23ac61;
}

ul.menu li.disabled:hover {
  background-color: #e0e0e0;
  cursor: default;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="projects">
  <ul class="menu" id="projects-menu">
  </ul>
</div>

Desired Output https://i.sstatic.net/7OXeX.png

Answer №1

If you want to create all the sub li elements, you can utilize the following method:

Object.values(data.info): ...retrieve an array containing the property values of a specified object...

Based on your feedback, I have introduced a new function named createList:

  • 1st parameter: where to add the newly generated list
  • 2nd parameter: the object or an array of objects
  • 3rd parameter: the value of the clicked element to search within the object(s)

Updated Code Snippet:

function createList(AppendToEle, obj, searchFor, currEle) {
  var objToUse = null;

  if (obj.constructor == Array) {
      obj.forEach(function(ele) {
          if (ele.project_name.toLowerCase() == searchFor.toLowerCase()) {
              objToUse = ele;
          }
      });
  }
  if (obj.constructor == Object) {
      if (obj.project_name.toLowerCase() == searchFor.toLowerCase()) {
          objToUse = obj;
      }
  }
  if (objToUse != null) {
      if (AppendToEle.find('.divList.' + objToUse.project_name.toLowerCase()).length != 0) {
          if ($(currEle).is('.selected')) {
              AppendToEle.find('.divList.' + objToUse.project_name.toLowerCase()).parent().remove();
          } else {
              console.log('Error: list (' + objToUse.project_name.toLowerCase()+  ' ) already created!');
          }
          return;
      }

      var div = $('<div/>');
      div.append($('<ul/>', {class: 'divList ' + objToUse.project_name.toLowerCase()}).append($('<li/>', {value: objToUse.project_name, text: objToUse.project_name})
              .prepend('<span class="glyphicon glyphicon-triangle-bottom">&nbsp;</span>')).append($('<ul/>')));
      Object.values(objToUse.info).forEach(function(val) {
          div.find('ul:last').append($('<li/>', {value: val, text: val}));
      });
      div.find('ul:first').on('click', function(e) {
          var isVis = !$(this).find('ul').is(':visible');
          $(this).find('ul').toggle(isVis);
          $(this).find('span.glyphicon ').toggleClass('glyphicon glyphicon-triangle-top glyphicon glyphicon-triangle-bottom');
      })
      AppendToEle.append(div);
  }
}

var data = {
  project_name: 'Sales1',
  info: {
      Value1: 'Value1',
      Value2: 'Value2'
  }
};
var data1 = [{
  project_name: 'Sales2',
  info: {
      Value1: 'Value2',
      Value2: 'Value2'
  }
},
  {
      project_name: 'Sales1',
      info: {
          Value1: 'Value1',
          Value2: 'Value1'
      }
  }];

$('#projects-menu').append("<li  value='sales1'>Sales 1</li>")
$('#projects-menu').append("<li  value='sales2'>Sales 2</li>")

$(document).on('click', '#projects-menu > li', function (event) {
  event.preventDefault();
  if (event.ctrlKey) {

      // dynamically create the list...
      createList($('body'), data1, this.getAttribute('value'), this);

      if ($(this).hasClass('selected')) {
          $(this).removeClass('selected');
      } else {
          $(this).addClass("selected");
      }
  } else {
      $("#projects-menu > li").removeClass("selected");
      $(this).addClass("selected");
  }
});
ul.menu {
    margin-top: 30px;
    list-style-type: none;
}

ul.menu li {
    background-color: #e0e0e0;
    padding: 8px 12px;
    border: solid 2px white;
    cursor: pointer;
    border: 3px solid #FFFFFF;
    border-radius: 10px;
}

ul.menu li:hover {
    background-color: #A9A9A9;
}

ul.menu li.selected {
    background-color: #23ac61;
}

ul.menu li.disabled:hover {
    background-color: #e0e0e0;
    cursor: default;
}

ul.divList li {
    list-style-type: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<div class="projects">
    <ul class="menu" id="projects-menu">
    </ul>
</div>

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

Customize the List Box Appearance for a Specific HTML Item (Option)

I am working on achieving a specific behavior. When using a listBox (or comboBox), the first element (such as "choose one") should have a unique style. Here is an example of code to test: <style type="text/css"> .testX {font-style: italic;} </ ...

JavaScript Brainfuck Compiler

I successfully created a BrainFuck compiler in JavaScript, which functions perfectly with this input: ++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.--- ...

Deciphering a JSON Array in JavaScript to extract specific components

I have a brief snippet for a JSON array and a JavaScript function that currently returns a single argument: <!DOCTYPE html> <html> <body> <h2>JSON Array Test</h2> <p id="outputid"></p> <script> var arrayi ...

Most efficient method for updating ASP.NET page with Javascript

I am currently working on a project in ASP.net where I have to handle a large number of questions stored in XML format. My first challenge was to render these questions dynamically on a web page using RadioButtonLists and a placeholder called sectionHolder ...

"Maximizing efficiency with Jquery and handling multiple AJAX requests simultaneously on a

Thumbnails are displayed on a page in the following manner: <div id="credits"> <a href="largeimage1.jpg" alt="credits1.php"><img src="thumb1"></a> <a href="largeimage2.jpg" alt="credits2.php"><img src="thumb2"></a> ...

Extracting the name from a JSON key/value pair and then adding it to a TextField

Here is a sample JSON data: { "Id": 1, "Title": "Information on Jane Smith", "Comments": "Additional details here", "UpdatedBy": "Jane Smith", "UpdateDate": "May ...

Dynamic div that automatically adjusts its height ratio to fit its parent container

Imagine you have two divs (A) and (B). The parent div (A) has a height: auto and so does the child div (B). Is there a way, without using JavaScript, to make div (B) always occupy 90% of the height of div (A)? Any insights or suggestions would be greatly a ...

Storing data as a JSON string in a JavaScript object and saving it to

Have you ever wondered why the cart object is saved as "cart" in the local storage instead of being an actual object? This discrepancy is causing the cart not to display correctly. This issue arose after deploying the website on Vercel. Storing "cart" as ...

Troubleshooting Issues with JavaScript Counter and JSON Integration

When manually inserting a number into the HTML, the counter works fine. However, when pulling data remotely, there seems to be a problem. The remote data is logging correctly in the console and appears properly in the DOM element when the counter code is d ...

What is the method for displaying the html required attribute in Django forms?

I am encountering an issue with a form field in Django. The email field is defined with the required attribute, but when rendered in HTML, it is missing the required attribute and is using type "text" instead of "email". The max_length attribute is, howeve ...

Are you harnessing the power of Ant Design's carousel next and previous pane methods with Typescript?

Currently, I have integrated Ant Design into my application as the design framework. One of the components it offers is the Carousel, which provides two methods for switching panes within the carousel. If you are interested in utilizing this feature using ...

Rendering with ReactDom in a SharePoint Framework application

Our current project requires us to generate a PDF file using the <div></div> elements. Most of the code I've seen renders from ReactDom.Render() instead of the render class: Take for instance React-pdf: import React from 'react&apo ...

Utilizing jQuery to scrape HTML and dynamically manipulate elements

Is there a way to retrieve HTML content from a different subdomain and incorporate it into the current site? HTML snippet: <head> <body> <div id = "items"> <div id = "#one"> <ul> <li><a href = "#">C ...

Tips for setting the tabindex on an element that has an opacity of 0

I have created a drag and drop image upload field with a hidden input element to style the upload button according to the design. However, I am concerned about accessibility and want the upload functionality to trigger when the user presses 'Enter&apo ...

Adding space between the cells on the far left and far right of the table and the border

I need some advice on creating a table in HTML where the borders of the leftmost and right most cells do not extend all the way to the edges of the table. Here's an example: | ____ | In this example, the top border of the cells is continuous within ...

Utilize external options for Chart.js datasets with added functionality

Exploring Chart.js for the first time in my project, I have found it to be a great tool. However, I've come across a challenge where I need to provide external filter options for the dataset as well. Currently, the filtering is done by clicking on lab ...

One-time execution of timed event

I'm struggling to get this function working properly. In my system, users can approve or disapprove a post by clicking on a link. All the content is loaded using ajax calls. When a user clicks, an alert pops up indicating success or error and then r ...

Align a flex item at the center of its parent when the parent has a flex direction of column

My challenge is aligning a flex item vertically within the remaining space allocated to it. This is my current code snippet: <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="82e0e ...

Hide dropdown when clicked outside of it

Can someone help me modify my JavaScript code so that when I click on a new dropdown, it closes the previous one and keeps only the current one open? function manageDropdowns() { var dropdowns = document.querySelectorAll('.dropdown:not(.is-hove ...

Creating a mobile/tablet friendly menu design

I'm currently working on designing a menu. I have made it look pretty nice so far, but I am facing an issue when the menu is viewed on mobile or small tablets. I want the menu to disappear and be replaced by a "MENU" button instead. Does anyone have ...