html无限层次结构输入到表单

时间:2018-06-07 08:26:29

标签: javascript html categories

我想添加用于添加新类别的表单。类别可能具有不定的子类别。



$(document).ready(function () {
    var max_fields = 15; //maximum input boxes allowed
    var wrapper = $(".input_fields_wrap"); //Fields wrapper
    var add_button = $(".add_field_button"); //Add button ID

    var x = 1; //initlal text box count
    $(add_button).click(function (e) { //on add input button click
        e.preventDefault();
        if (x < max_fields) { //max input box allowed
            x++; //text box increment
            $(wrapper).append('<div class="input_fields_wrap_sec"><input type="text" name="mytext[]" placeholder="Sub-Category title"/>\n\
                                <input type="submit" name="submit1" value="Add Sub-Sub-Category" class="add_field_button" >\n\
                                <a href="#" class="remove_field">Remove</a></div>'
                    ); //add input box
        }
    });

    $(wrapper).on("click", ".remove_field", function (e) { //user click on remove text
        e.preventDefault();
        $(this).parent('div').remove();
        x--;
    });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="POST">
   <div class="input_fields_wrap">
      <p>Please enter the Category Title</p>
      <input type="text" name="mytext[]" placeholder="Category title">
      <input type="submit" name="submit1" value="Add Sub-Category" class="add_field_button" >
   </div>
   <input type="submit" name="submit" value="submit">
</form>
&#13;
&#13;
&#13;

现在我有this的形式,当我按下&#34;添加子子类别&#34;它应该是新的&#34;子子类别&#34;用按钮输入:&#34;添加子子类别&#34;和&#34;删除&#34;

它应该像this,类别的深层是不定式的

1 个答案:

答案 0 :(得分:0)

的LABAs!

您可以尝试这样的事情:

function getValueText(level) {

  let i = 0
  let text = "Add ";
  while (i < level) {
    text += "sub-"
    i++;
  }

  return text + "category";
}

function appendInnerCategory(level, element) {
  var myDiv = document.createElement("div");
  myDiv.className = "level-" + level
  var btn = document.createElement("input");
  btn.type = "button";
  btn.value = getValueText(level);
  btn.addEventListener("click", function(event) {
    appendInnerCategory(level + 1, event.target.parentNode);
  });
  var textBox = document.createElement("input");
  textBox.type = "text";
  myDiv.appendChild(textBox);
  myDiv.appendChild(btn);
  element.appendChild(myDiv);
}

appendInnerCategory(0, document.querySelector('.wrapper'));

HTML:

<div class="wrapper"></div>

小提琴:http://jsfiddle.net/7L382gow/

在操作DOM时更新了维护结构对象的小提示。

提交会将生成的层次结构打印到控制台。

http://jsfiddle.net/bqk6pmjg/