[英]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.