views:

638

answers:

5

By default I have 5 textboxes. When a user clicks on a button, one textbox should be added.

How could I do this?

A: 

Best would be to attach an event on to the onclick of the button, that will set a div's visibility to inline. This is about the best way I can see for this, considering flexibility and robustness.

Have a look here for example code.

Kyle Rozendo
A: 
<script>
function add()
{
    document.getElementById("place").innerHTML="<input type='text' value=''>"
}
</script>
<input type="button" value="clickMe" onClick="add();">
<div id="place"></div>
x2
Whomever voted for this, isn't aware of the impact of using innerHTML.
OMG Ponies
A: 

try this

<html>
<head>
<title>Dynamic Form</title>
<script language="javascript" type="text/javascript" >
function changeIt()
{

createTextbox.innerHTML = createTextbox.innerHTML +"<br><input type='text' name='mytext' >"

}
</script>
</head>
<body>

<form name="form">
<input type="button" value="clickHere" onClick="changeIt()">
<div id="createTextbox"></div>
</form> 
</body>
</html>
anishmarokey
Whomever voted for this, isn't aware of the impact of using innerHTML.
OMG Ponies
-1. Mucking about with `innerHTML` when a simple `appendChild()` would work is unnecessarily slow, and what is going on with your `i` variable? It doesn't even get used because the variable isn't expanded in the `innerHTML` string, so your HTML becomes `name='mytext'` followed by garbage that the browser can't understand.
Daniel Pryden
Writing to innerHTML once is fair enough; += on innerHTML is always a mistake.
bobince
+5  A: 

If you replace the innerHTML, the previously entered values will be cleared, to avoid that, you can append the input elements programmatically:

var input = document.createElement('input'); 
input.type = "text"; 
//...    
container.appendChild(input);

Check this example.

CMS
Correct answer - because innerHTML will replace the contents of the specified HTML element with the newly defined innerHTML value.
OMG Ponies
+1  A: 
<script>
function add()
{
    var inpt = document.getElementById('input_template');
    inpt.parentNode.appendChild(inpt.cloneNode(false));
}
</script>

<input type="button" onclick="add();">

set id=input_template to one of the predefined textboxes

w35l3y
I would have made it a separate function instead of inline, and I would have used CSS to keep the styles the same, but this does seem like a clever way to do it, and it does seem it would work.
Daniel Pryden
FYI: Better formatting would help everyone.
OMG Ponies