Lemon Kazi Lemon Kazi - 1 year ago 120
Javascript Question

After click append child with input field like tree

I am trying to create organization structure with left child and right child.
just like this demo

But I want to save data from here with input field.
I want to create left child and right child for each after click. now all displaying one after one in bottom and only remove button. I want add button also for creating child for each input form.
Here I used like this

$(function() {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').size() + 1;

$('#addScnt').live('click', function() {
$('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt_' + i + '" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv);
return false;

$('#remScnt').live('click', function() {
if (i > 2) {
return false;

* {
font-family: Arial;
h2 {
padding: 0 0 5px 5px;
h2 a {
color: #224f99;
a {
color: #999;
text-decoration: none;
a:hover {
color: #802727;
p {
padding: 0 0 5px 0;
input {
padding: 5px;
border: 1px solid #999;
border-radius: 4px;
-moz-border-radius: 4px;
-web-kit-border-radius: 4px;
-khtml-border-radius: 4px;

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<h2><a href="#" id="addScnt">Add Another Input Box</a></h2>

<div id="p_scents">
<label for="p_scnts">
<input type="text" id="p_scnt" size="20" name="p_scnt" value="" placeholder="Input Value" />

Here is jsfiddle DEMO
I want to create tree structure same as that plugin with input form. but failed to do that. my snippet is not working in question so I placed jsfiddle link.

Answer Source

There are various errors in your code mainly the id's should be unique. And use on() instead of live() since it's depreciated in new versions. You can do something like this with use of table , it's a simple demo you need to update it

$("#main").on('click', '.add', function() {
  var $td = $(this).parent();
  var $td1 = $('<td>', {
    html: '<input  />      <button class="add">+</button>      <button class="remove">-</button>'
  var $tbl = $td.children('table')
  if ($tbl.length)
    $td.append($('<table>', {
      html: $('<tr>', {
        html: $td1
}).on('click', '.remove', function() {
input {
  width: 20px
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="main" style="width:100%;text-align:center">
      <input type="text" id="p_scnt" size="20" name="p_scnt" value="" placeholder="Input Value" />
      <button class="add">
      <button class="remove">