Hello, Im working on a script that adds a <input type='text'> to a form when clicking on a button. Here is the code: <html> <head> <script language="javascript"> var counter = 0; function addPerson() { counter++; document.getElementById("divq").innerHTML += "Person " + counter + ": <br><input type='text' name='q" + counter + "' value='' /><br><br>"; } </script> </head> <body> <input type="button" onclick="addPerson()" value="Add Person" /> <form> <div id="divq"> </div> </form> </body> </html> Code (markup): Now to my problem: when I add a new input by clicking on the button all formerly created inputs gets everything that I have wrote in them reseted. How can I solve that?
Try changing your function addPerson to the following. I tried it and it works: function addPerson() { counter++; var divq = document.getElementById("divq"); var newdiv = document.createElement("div"); newdiv.id = 'div'+counter; divq.appendChild(newdiv); document.getElementById(newdiv.id).innerHTML += "Person " + counter + ": <br><input type='text' name='q" + counter + "' value='' /><br><br>"; } Code (markup):