I have this code that appends a div that contains input fields and textareas to a parent div on click of a button. when I append the div and input some values in the fields and then append a new div, the values of the input fields somehow becomes empty. how can it fix this problem?
here is the code:
let counter = 1;
let new_section = document.getElementsByClassName("addnew")[0];
document.getElementById("shownew").addEventListener("click", (e) => {
e.preventDefault();
new_section.innerHTML += ` <div class="lowerlayer2">
<input type="text" placeholder="Word Type" id="wtype${counter}" />
<input type="text" placeholder="Synonym" id="syn${counter}" />
<input type="text" placeholder="Antonyms" id="anty${counter}" />
<textarea
cols="30"
rows="10"
placeholder="History & Etymology"
id="history${counter}"
></textarea>
<textarea
cols="30"
rows="10"
placeholder="Examples"
id="example${counter}"
></textarea>
<textarea
cols="30"
rows="10"
placeholder="Definition 1"
id="def1${counter}"
></textarea>
</div>`;
counter++;
});
innerHTML+=...re-sets the value with a new string so all the contents of the element get removed, the the new html string is parsed and new elements made. If you want to add elements without destroying/recreating previous content useinsertAdjacentHTML()orinsertAdjacentElement()new_section.innerHTMLyou are not appending, but overwriting the content of thisnew_section. Try reading up oninsertAdjacentHTMLinsertAdjacentHtml()worked