Stop input from clearing on innerHTML tab

I am working on a form that allows the user to add additional input fields by clicking a button.

It basically looks like this:

<div>
   <input type="text" placeholder="existing"/>
</div>

<button class="add">add</button>

With a little JavaScript:

var add = document.querySelector(".add");
var div = document.querySelector("div");

add.addEventListener('click', function () {

    div.innerHTML += '<input type="text" placeholder="new"/>';

});

However, I noticed that when the button is clicked - if any existing input fields have values, they are cleared.

I have been doing this for a while and can't find a solution to stop this, so I wonder if anyone here can help.

Here's the script http://jsfiddle.net/gxzLZ/

+4
source share
4 answers

If you try console.log(div.innerHTML), you will see the printed HTML:

<input type="text" placeholder="existing"><input type="text" placeholder="new">...

- <input>, . div

: http://jsfiddle.net/gxzLZ/5/

JS

var add = document.querySelector(".add");
var div = document.querySelector("div");

add.addEventListener('click', function () {
    var input = document.createElement('input')
    input.type = "text";
    input.placeholder = "new";
    div.appendChild(input);
});
+3

, outerHTML, appendChild.

add.addEventListener('click', function () {
    var newInput = document.createElement('input');
    newInput.outerHTML = '<input type="text" placeholder="new"/>';
    div.appendChild(newInput);

});

+1

- ?

HTML

<div id="div"><input type="text" placeholder="existing" id="input"/></div>
<button class="add">add</button>

JAVASCRIPT

var add = document.querySelector(".add");
var div = document.querySelector("div");

add.addEventListener('click', function(){
    var cloned = document.getElementById('input').cloneNode(true);
    cloned.value = '';  // cloned will have no value
    document.getElementById('div').appendChild(cloned);
}, false);

cloneNode . , ,

FIDDLE

0

,

div.innerHTML += '<input type="text" placeholder="new"/>';,

, div.innerHTML div.innerHTML+'<input type="text" placeholder="new"/>', HTML-, reset.

:

var inp = document.createElement("input");

inp.type="text";

document.body.appendChild(inp);.

0
source

Source: https://habr.com/ru/post/1544165/


All Articles