A
A
Alexey Ochkasov2021-06-25 13:03:28
JavaScript
Alexey Ochkasov, 2021-06-25 13:03:28

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++;
}

Its task is to add input fields when you click on the button. He does it. But at the same time it clears all the previous fields. In addition to adding new ones, it updates old ones. Why is this happening?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Shohruh Shaimardonov, 2021-06-25
@DeD0k_CtaT1cT

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 question

Ask a Question

731 491 924 answers to any question