Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I infinitely add children to this list tree?

Tags:

html

jquery

css

I want to be able to infinitely add children/grandchildren/greatgrandchildren/etc. to this tree I am making. Currently I have it set up so it only goes 3 levels deep and I can't figure out a way to have it go as deep as the user wants.

HTML

<div class="tag-tree">
<ul id="addParent">
  <li class="root" class="add-child">
    <input /> <p class="add-child-field"><i class="fa fa-plus"></i></p>
  </li>
  <li>
    <input />  <p class="add-gc-field"><i class="fa fa-plus"></i></p>      
    <ul> 
  <li><input /></li>
  <li><input /></li>
  <li><input /></li>
    </ul> 
  </li>
  <li><input /> <p class="add-gc-field"><i class="fa fa-plus"></i></p>   </li>
  <li>
    <input /> <p class="add-gc-field"><i class="fa fa-plus"></i></p>   
<ul>
  <li><input /></li>
  <li><input /></li>
</ul>  
  </li>
</ul>  
<div class="add-field"><i class="fa fa-plus"></i> New Parent Tag</div>
</div>

jQuery

$(".add-field").click(function() {
  $('#addParent').append('<li class="root" id="addChild"><input /> <p class="add-child-field" onclick="add_child();"><i class="fa fa-plus"></i></p></li>')
});

$(document).on('click', ".add-child-field", function() {
  $(this).parent().after('<li><input /><p class="add-gc-field"><i class="fa fa-plus"></i></p> </li>');
});



$(document).on('click', ".add-gc-field", function() {
  if ($(this).next('ul').length) {
    console.log(this)
    $(this).next('ul').append('<li><input /></li>');
  }
  else {
    console.log(this)
    $(this).after('<ul><li><input /></li></ul>');
    }
});

http://jsfiddle.net/y6ekn7d2/

like image 891
user3277733 Avatar asked Apr 23 '15 16:04

user3277733


1 Answers

I took the liberty to simplify your code a little bit.

In order to maintain an arbitrary number of levels I treated all inputs same except the root ones. So that they all execute the same code to maintain their sublists. But the prevent the confusion, I added all input elements a "level" index.

<li>
  <input data-level="XXX" />
  <p class="add-field">
    <i class="fa fa-plus"></i>
  </p>
</li>

Here is a modified version of your fiddle

http://jsfiddle.net/y6ekn7d2/2/

like image 125
JuniorDev Avatar answered Sep 19 '22 09:09

JuniorDev