11

I have a form that is generated via ajax based of a multi-file uploader (swfupload). It adds more form elements to a given dom element upon the completion of each file uploaded. This thus gives me a problem. If i selected 5 files to upload, the first file will generate a form which I will start entering data in, however, when the 2nd file is completed uploading, it clears the previous entered data in the form elements and also appends the 2nd form elements.

I think this is because im using:

document.getElementById('test').innerHTML = document.getElementById('test').innerHTML + newformelements;

I think doing the above doesn't keep any entered data in the forms, just the HTML itself.

So, how can I append to this element without destroying what has been put into form fields already? The number of possible children is dynamic based of the multi-uploader.

David
  • 16,246
  • 34
  • 103
  • 162
  • 1
    You won't believe this but there are actually DOM manipulation functions for that `:P`, don't use innerHTML - DOM recreation via innerHTML should be avoided! – Šime Vidas Sep 06 '11 at 15:53
  • I think you are mistaking what innerHTML is for. Are you requiring a table of somekind, that dynamically extends according to new data? – T9b Sep 06 '11 at 15:56
  • @David Depends... Are all those forms identical (in which case you could just clone an existing template form)? Where do you get the HTML source code for the forms? Is it hard-coded into the HTML source code of the web-page itself? – Šime Vidas Sep 06 '11 at 16:02
  • 1
    See http://stackoverflow.com/a/9851500/753129 – alnafie Dec 11 '13 at 10:01

3 Answers3

7

Use DOM manipulation, in this case: Node.appendChild [docs].

innerHTML will always destroy and recreate the elements.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
7

Are you open to use jquery? If yes then You can easily do something like this

$("#divid").append("html you want to append");
Pa.M
  • 1,392
  • 1
  • 10
  • 15
0

Create a new element, set its innerHTML, than append it to the end of the forms' children.

Jon Adams
  • 24,464
  • 18
  • 82
  • 120