Answer the question
In order to leave comments, you need to log in
Why are old input fields cleared when new ones are added?
Hello. I am new to JavaScript. I have this code.
<div id="inputing">
<h4>Ингредиенты</h4>
<div id="input01">
<label><input type="text" name="ingredient0"></label>
<label><input type="text" name="quantity0"></label>
<label><input type="text" name="quantity_spoon0"></label>
</div>
</div>
<input type="button" value="Добавить" onclick="addInput()">
let x = 0;
function addInput() {
let str = '<div id="input' + x + '"></div>';
document.getElementById('inputing').innerHTML += str;
let str2 = '<label><input type="text" name="ingredient' + (x + 1) + '"></label><label><input type="text" name="quantity' + (x + 1) + '"></label><label><input type="text" name="quantity_spoon' + (x + 1) + '"></label>';
document.getElementById('input' + x).innerHTML = str2;
x++;
}
Answer the question
In order to leave comments, you need to log in
Because when a nested tag is "added" through `innerHTML`, then js takes the html content, and the value of the field that was entered into the field was not displayed anywhere in the DOM tree at that moment, from where such a problem
Decisions 2:
1. (crutch) every time the value of the fields is changed, write the values to the value attribute of the input, so when you call your function, the current value of the field will be in `innerHTML` and when a new one is added, it will be cleared
2. (correct approach) you need to create nodes and insert them according to normal, i.e. first document.createElement('TAGNAME') and then parentElement.append(PREVIOUS_CREATED_TAG)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question