Jack TC
Jack TC

Reputation: 344

Javascript deleting form input adding to innerHTML

I've been having a problem with the javascript "innerHTML" function when using forms. I've been adding more options to a form (and sending them to the server in an array e.g. foo[] ). The problem is, if the user presses to add another element to the form to add another option, the previous options they have selected are deleted.

What I want to happen is just add another element of the same type inside a tag. I am targeting IE9 and not using any frameworks. I am using:

document.getElementById("contents").innerHTML += this.item;

Where this.item is the code I want to add to the end of the row.

What I'm wondering is, would recursing through a tree of the code I want to add to create a node tree and then using appendChild be the best way to do it, or is there a better way?

Upvotes: 3

Views: 3184

Answers (2)

Esailija
Esailija

Reputation: 140210

Literally never use innerHTML +=, it will mess up everything.

insertAdjacentHTML is meant for these cases and has been supported since IE4

So:

document.getElementById("contents").insertAdjacentHTML( "beforeend", this.item )

Upvotes: 13

jfriend00
jfriend00

Reputation: 707258

You will need to add individual DOM objects, not add onto innerHTML like you are doing.

What your code document.getElementById("contents").innerHTML += this.item; does is get the contents of innerHTML as a string (which doesn't include things that have been typed into form elements), add onto the end of the string and then set it back. Not only does it mess up form elements, but it messes up all event handlers too because it destroys and recreates all the DOM elements that are children of the parent "contents".

This is a classic example of when it's bad to use innerHTML when the parent contains other objects. If you're just trying to add onto the end of the contents of innerHTML, you should just create your own DOM elements and append them to the end of contents. Here's how you could append some simple text without that issue:

var span = document.createElement("span");
span.innerHTML = this.item;
document.getElementById("contents").appendChild(span);

Upvotes: 4

Related Questions