Build a JSON class from existing <ul> html

292
November 21, 2016, at 9:58 PM

I have a jQuery plugin that displays an organization chart based off a <ul> heirarchy.

This will allow my users to drag and drop employees around, and once dropped, an event fires telling me the DOM has changed. At this point I want to read the <ul>, and build a JSON class off it so I can send it to my server (ASP .NET MVC) for further processing.

Are there any libraries out there that can do this for me, and if not, how would I go about doing it myself?

An example of the html:

<ul id="org" style="display:none">
<li>
  Food
  <ul>
    <li>Beer</li>
    <li>Vegetables
      <ul>
        <li>Pumpkin</li>
        <li><a href="http://tquila.com" target="_blank">Aubergine</a></li>
      </ul>
    </li>
    <li>Bread</li>
    <li>Chocolate
      <ul>
        <li>Topdeck</li>
        <li>Reese's Cups</li>
      </ul>
    </li>
  </ul>
</li>
</ul>
Answer 1

You need to loop through the dom node and create the proper json as following:

var getTreeData = function(parentNode){
    var nodes = [];
    var $parentNode = $(parentNode);
    $parentNode.children('li').each(function(index, li){
    var nodeData = {};
    var nodeText = $(li).contents().filter(function() {
  return this.nodeType == 3;
}).text();
    nodeData.text = nodeText.trim().replace('\n', '');
    if($(li).children('ul').length>0){
        nodeData.children = getTreeData($(li).children('ul'))
    }
        nodes.push(nodeData);
    });
    return nodes;
}

Now call the getTreeData function passing the parent tree ul as following:

var treeData = getTreeData($('#org'));

Here is the complete fiddle example: https://jsfiddle.net/rxwy4zqw/

Rent Charter Buses Company
READ ALSO
How to have a click event for button in jquery?

How to have a click event for button in jquery?

here what i am trying to do is when i click on the button i want to get a confirm box and if i press ok the data must be deleted. I have done using ajax.

446
How to move tr by parameter?

How to move tr by parameter?

I am having second table constructions:.

456
How to disable jqgrid row cell?

How to disable jqgrid row cell?

I want to disable row cell in Jqgrid in loadcomplete. I am using this code:.

636