Need help with my form-creating script

Discussion in 'JavaScript' started by Cratylus, Feb 15, 2010.

  1. #1
    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?
     
    Cratylus, Feb 15, 2010 IP
  2. mps705

    mps705 Peon

    Messages:
    55
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    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):
     
    mps705, Feb 15, 2010 IP