表单字段:通过Javascript </form> </inputs>将新的<inputs>添加到<form>的内部

时间:2013-03-22 13:48:36

标签: javascript forms

我正在尝试通过按钮将新字段添加到我的表单中。但是,它会将其添加到表单的外部。关于要编辑什么来实现这一目标的任何想法?感谢。

我的HTML:

<div id="page">

<h1>Quick Order</h1>
<div id="dynamicInput">
<form method="post" name="QuickOrderMulti">

<input type="hidden" name="formName" value="dmiformQuickOrderMulti">

  <p>Product #  <input type='Text' name="ProductNumber" title="Enter Product #"></p>
  <p>Product #  <input type='Text' name="ProductNumber" title="Enter Product #"></p>


<input type="submit" value="Add"><input type="button" value="Add another text input"     onClick="addInput('dynamicInput');">

</form>
</div>
</div> <!-- page -->

我的JavaScript:

<script type="text/javascript">
var counter = 0;
var limit = 3;
function addInput(dynamicInput){
     if (counter == limit)  {
          alert("You have reached the limit of adding " + counter + " inputs");
     }
     else {
          var newdiv = document.createElement('div');
          newdiv.innerHTML = "Product # " + (counter + 1) + " <br><input type='text'     name='ProductNumber[]'>";
          document.getElementById(dynamicInput).appendChild(newdiv);
          counter++;
     }
}
</script>

3 个答案:

答案 0 :(得分:0)

您将附加到表单周围的DIV,因此字段不会出现在子表单中。

将表单放在“dynamicInput”div周围...或者在表单内插入。

选项A:

<form method="post" name="QuickOrderMulti">
  <div id="dynamicInput">
  ...
  </div>
</form>

选项B:

<div id="dynamicInput">
  <form method="post" name="QuickOrderMulti" id="QuickOrderMulti">
  ...
  </form>
</div>

<script type="text/javascript">
  ...
  document.getElementById('QuickOrderMulti').appendChild(newdiv);
                           ^^^^^^^^^^^^^^^
  ...
</script>

答案 1 :(得分:0)

您将输入添加到div,而不是表单。只需给表单一个id并将输入字段添加到该表单。

document.getElementById("formId").innerHTML = "Product # " + (counter + 1) + " <br><input type='text'     name='ProductNumber[]'>";

答案 2 :(得分:0)

尝试:

<script type="text/javascript">
var counter = 0;
var limit = 3;
function addInput(dynamicInput){
 if (counter == limit)  {
      alert("You have reached the limit of adding " + counter + " inputs");
 }
 else {
 var parent = document.getElementById('myform')
 var element = null;
 try { // IE
 element = document.createElement('<input type="text" name="ProductNumber[]">');
 } 
 catch (e) { // W3C
 element = document.createElement("input");
 element.setAttribute("type", "text");
 element.setAttribute("name", "ProductNumber[]");
  }
 parent.appendChild("Product # " + (counter + 1) + element);
 counter++;
  }
}
 </script>