ceadreak
ceadreak

Reputation: 1684

Jquery nestable / initialize list from json

I'm using the jquery nestable plugin (https://github.com/dbushell/Nestable/blob/master/jquery.nestable.js) to generate a nestable list.

Generation of a json output and save it into a database is not a problem.

Example of json generate by this plugin :

[{"id":4,"children":[{"id":3}]}] 

The question is : How can I construct the nestable list from the same json array ?

Upvotes: 0

Views: 4779

Answers (3)

Dave
Dave

Reputation: 4436

Ozan's answer works well but if you need more advanced configuration then here is the link https://github.com/RamonSmit/Nestable2

Upvotes: 0

Aamir Shaikh
Aamir Shaikh

Reputation: 83

we all have seen how to add items dynamically to nestable. I have written this code, where in you can create nestable items from JSON object.

var json =  [{
  "id": 1,
  "content": "Payment Terms",
  "children": [{
    "id": 2,
    "content": "PT1"
  }, {
    "id": 3,
    "content": "PT2"
  }]
}, {
  "id": 4,
  "content": "Delivery Terms",
  "children": [{
    "id": 5,
    "content": "dt1"
  }, {
    "id": 6,
    "content": "dt2"
  }]
}];

Function to create nestable :

function makeNestableListUsingJSONArray(jsonArray, root) {

  if (typeof root === 'undefined') {
    root = $('body');
  }
  var $div = $('<div id="nestable"><ol class="dd-list"></ol></div>');
  root.append($div);
  for (var i = 0; i < jsonArray.length; i++) {
    var $li = $("<li class='dd-item' data-id='" + jsonArray[i].id + "'><div class='dd-handle'><span class='dd-content'>" + jsonArray[i].content + "</span></div></li>");
    root.find('ol.dd-list:first').append($li);    

    if (typeof jsonArray[i].children !== 'undefined') {
      makeNestableListUsingJSONArray(jsonArray[i].children, $li);
    }
  }
  $('#nestable').nestable({maxDepth:2});
}

call the function 
makeNestableListUsingJSONArray(json);

Upvotes: 1

Ozan
Ozan

Reputation: 3739

You can just form the required html from the array you have. Just wrap it up in a function that handles the nested elements (can be done by calling on itself) and returns the <ol> list.

var tarr = [{"id":4,"children":[{"id":3}]}];

function listify(strarr) {
  var l = $("<ol>").addClass("dd-list");
  $.each(strarr, function(i, v) {
    var c = $("<li>").addClass("dd-item"),
      h = $("<div>").addClass("dd-handle").text("Item " + v["id"]);
    l.append(c.append(h));
    if (!!v["children"])
      c.append(listify(v["children"]));
  });
  return l;
}

var list = listify(tarr);
$("#test").append(list);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="test"></div>

Upvotes: 2

Related Questions