SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Guru JoePrice's Avatar
    Join Date
    Jan 2002
    Location
    UK
    Posts
    673
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    How to keep form input value when adding a new input text box with javascript?

    Hi guys

    I've written a javascript function that adds a new form input box when a button is pressed. The problem is that when I add text to an input textbox and then press "add a new button" the contents of the previous input textbox is lost.

    Here is my javascript code, can anyone help me keep my input value when adding a new input textbox?
    Code:
        document.addQuestion.answerCount.value = parseFloat(document.addQuestion.answerCount.value) + 1;
        var x = document.getElementById("inputs");
        x.innerHTML += "<input type=\"text\" class=\"questionAnswerBox\" name=\"answer"+document.addQuestion.answerCount.value+"\"/>";
    Many thanks for all your suggestions.

  2. #2
    I meant that to happen silver trophybronze trophy Raffles's Avatar
    Join Date
    Sep 2005
    Location
    Tanzania
    Posts
    4,662
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Try using DOM methods instead of innerHTML.
    Code Javascript:
    var i = document.createElement('input'), x = document.getElementById("inputs");
    i.type = 'text';
    i.className = 'questionAnswerBox';
    i.name = 'answer'+document.addQuestion.answerCount.value;
    x.appendChild(i);

  3. #3
    SitePoint Guru JoePrice's Avatar
    Join Date
    Jan 2002
    Location
    UK
    Posts
    673
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi Raffles,

    Thanks for the suggestion it works a treat.
    Do you know how to add a select with various options as well with this method?

    Thanks

  4. #4
    I meant that to happen silver trophybronze trophy Raffles's Avatar
    Join Date
    Sep 2005
    Location
    Tanzania
    Posts
    4,662
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Well, in the same way, use createElement with 'select' and then using appendChild, append option elements that you have also created using createElement. For the options cloneNode can come in handy, a loop is also a good idea if you have lots of them.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •