0

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

我的 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>
4

3 回答 3

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>
于 2013-03-22T13:50:53.483 回答
0

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

document.getElementById("formId").innerHTML = "Product # " + (counter + 1) + " <br><input type='text'     name='ProductNumber[]'>";
于 2013-03-22T13:53:18.680 回答
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>
于 2013-03-22T14:17:39.340 回答