Reputation: 53
I wanted to add textboxes dynamically and then pass the values written in these textboxes to
an array. here is my code.
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>
thanks....
Upvotes: 2
Views: 2014
Reputation: 1434
try this
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;
}
}
Working JSBin
example
http://jsbin.com/EPOtuno/1/edit
Upvotes: 2
Reputation: 386
Here try this!!!
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>
Upvotes: 3
Reputation: 38345
I imagine the problem is that the element isn't part of the document until you call foo.appendChild(element);
so doing document.getElementById('n'+c);
isn't returning anything. However, that's totally unnecessary anyway. If it were part of the document, document.getElementById('n'+c);
is just going to return exactly what you already have referenced by element
, so you should be able to just do:
a[c] = element;
Upvotes: 0