我创建了这部分代码。每当按下按钮时,表单中都会添加一个新的输入论坛字段。如何每次在字段旁边添加文本和数字(从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>
提前致谢! :)
答案 0 :(得分:0)
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>
答案 1 :(得分:0)
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++;
}