Lukas Lukas - 22 days ago 14
HTML Question

Adding a textbox to div without losing values

i've a div container and a button. Whenever i click the button, an empty textbox is added to the div. Now, my problem is whenever i click the button, the textbox is added, but the values of all others are removed.

The function is made like this:

function addTextBox() {
document.getElementById("txtList").innerHTML += "<input type='text'>";
}

Answer

What is happening under the hood here is that when you append the DOM as text using innerHTML you are simply rewriting that section of HTML. Editing your textList innerHTML will execute a new paint of that element and all information will be parsed again. This means you loose your user interaction.

To update your DOM elements successfully there are methods which enable you to do that. namely document.createElement and document.appendChild.

By appending the DOM element as opposed to concatenating the innerHTML(text) your are forcing a limited paint of the specific area. This leaves the rest of the DOM in tact.

Your code here

function addTextBox() {
    document.getElementById("txtList").innerHTML += "<input type='text'>";
}

Becomes more like the following

function addTextBox() {
    var textEl = document.getElementById("txtList");
    var input = document.createElement("input");
    input.type = 'text';

    textEl.appendChild(input);
}
Comments