Reputation: 383
I found this JavaScript online that adds input buttons when you press a button.
I changed it so that instead of being able to select which type of input you create it just automatically creates a textbox. But it's not working. What should I change?
function add(type) {
//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", "text");
element.setAttribute("name", "goal[]");
var foo = document.getElementById("fooBar");
//Append the element in page (in span).
foo.appendChild(element);
}
<INPUT type="button" value="Add" onclick="add(document.forms[0].element.value)"/>
<span id="fooBar"> </span>
Upvotes: 1
Views: 235
Reputation: 262929
Some browsers do not allow to set the name
attribute dynamically on an element.
You can specify the name
attribute in the markup passed to createElement()
to work around this problem:
var element = document.createElement("<input name='goal[]' type='text' />");
Upvotes: 0
Reputation: 83358
Your add function is correct, but I think something is broken here—document.forms[0].element.value
onclick="add(document.forms[0].element.value)"
Try changing it to
onclick="add()"
Since you're not using that type parameter anyway
Upvotes: 1