[英]Passing the values from dynamically created textboxes to an array using JavaScript only
我想动态添加文本框,然后将这些文本框中编写的值传递给
数组。 这是我的代码。
function add(type)
{
a=new Array();
for(c=0;c<3;c++)
{
var element = document.createElement("input");
element.setAttribute("type", type);
element.setAttribute("value", type);
element.setAttribute("name", type);
element.setAttribute("id", 'n'+c);
var foo = document.getElementById("fooBar");
a[i]=document.getElementById('n'+c);
foo.appendChild(element);
}
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<SELECT name="element">
<OPTION value="button">Button</OPTION>
</SELECT>
<INPUT type="button" value="Add" onclick="add(document.forms[0].element.value)"/>
<span id="fooBar"> </span>
谢谢....
在这里试试!
var a= [];
function add(type) {
for(c=0;c<3;c++){
var element = document.createElement("input");
element.setAttribute("type", type);
element.setAttribute("value", type);
element.setAttribute("name", type);
element.setAttribute("id", 'n'+c);
var foo = document.getElementById("fooBar");
foo.appendChild(element);
a[c]=document.getElementById('n'+c).value;
}
}
function show(){
for(c=0;c<3;c++){
alert(a[c]);
}
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<SELECT name="element">
<OPTION value="text">Text</OPTION>
</SELECT>
<INPUT type="button" value="Add" onclick="add(document.forms[0].element.value)"/><br>
<INPUT type=button name="b1" value="Show" onclick="show()"/><br>
<span id="fooBar"> </span>
尝试这个
HTML
<form>
<select name="element">
<option value="button">Button</option>
</select>
<input type="button" value="Add" onclick="add(document.forms[0].element.value)"/>
<span id="fooBar"> </span>
</form>
JS
function add(type)
{
a=new Array();
for(c=0;c<3;c++)
{
var element = document.createElement("input");
element.setAttribute("type", "text");
element.setAttribute("value", type);
element.setAttribute("name", "mytextbox");
element.setAttribute("id", 'n'+c);
var foo = document.getElementById("fooBar");
foo.appendChild(element);
a[c]=document.getElementById('n'+c).value;
}
}
工作JSBin
示例
我想问题是在您调用foo.appendChild(element);
之前,元素不是文档的一部分foo.appendChild(element);
这样做document.getElementById('n'+c);
什么也没退 但是,这绝对是不必要的。 如果它是文档的一部分,则为document.getElementById('n'+c);
将会完全返回您已经由element
引用的element
,因此您应该能够执行以下操作:
a[c] = element;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.