带有按钮和html的Javascript新输入字段

Javascript New Input Field With Button and html

本文关键字:输入 字段 新输入 Javascript 按钮 html      更新时间:2023-09-26

我已经创建了这部分代码。每当按下按钮时,表单中就会添加一个新的论坛输入字段。如何每次在字段旁边添加文本和数字(从3开始)?例如:选项1:输入类型字段选项2:输入类型字段选项3:输入类型字段等等

<SCRIPT language="javascript"> function add() {
//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", 'text');
element.setAttribute("value", '');
element.setAttribute("name", 'text[]');

var foo = document.getElementById("fooBar");
//Append the element in page (in span).
foo.appendChild(element);
}
</SCRIPT>

以下人员正在使用上述代码部分(仅供参考):

<b>Option 1:</b> <input type="text" name="text[]" /><br />
<b>Option 2:</b> <input type="text" name="text[]" />
<input type="button" value="Add Option" onclick="add()"/>
<span id="fooBar"></span>

提前感谢!:)

var temp = 3;
function add() {
var element = document.createElement("input");
var span = document.createElement("span");
    span.innerHTML = "Option "+temp;
//Assign different attributes to the element.
 element.setAttribute("type", 'text');
 element.setAttribute("value", '');
 element.setAttribute("name", 'text[]');

 var foo = document.getElementById("fooBar");
  foo.appendChild(span);
  foo.appendChild(element);
temp++;
}

 var optionCount = 3;
 function add() {
   //Create an input type dynamically.
   var element = document.createElement("input");
   var label = document.createElement("label");
   label.innerHTML = "Option " + optionCount++ +":"
     //Assign different attributes to the element.
   element.setAttribute("type", 'text');
   element.setAttribute("value", '');
   element.setAttribute("name", 'text[]');
   var foo = document.getElementById("fooBar");
   //Append the element in page (in span).
   foo.appendChild(label);
   foo.appendChild(element);
 }
<b>Option 1:</b> 
<input type="text" name="text[]" />
<br />
<b>Option 2:</b> 
<input type="text" name="text[]" />
<input type="button" value="Add Option" onclick="add()" />
<span id="fooBar"></span>