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/
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With