Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

184
Visualizações
Value in "input" filed becomes empty

Hi Folks I'm new to JS World.

I am trying to add A <div> dynamically to my HTML with the help of JavaScript.

var counter = 0;
function add_more_animals() {
    counter+=1;
    html = `<div id="animal${counter}">
            <input type="text" name="animalName${counter}">
            <input type="text" name="animalType${counter}">
            </div>`;

    var form = document.getElementById("animals");
    form.innerHTML+=html;
}
<div id="animals">
        <div id="animal0">
            <input type="text" name="animalName0">
            <input type="text" name="animalType0">
        </div>
</div>
<button type="button" onclick="add_more_animals()">Add animals (+)</button>

The issue I'm facing:

While I populate the fields of animalName0 and animalType0 on UI. After I click on add button so as to insert more animals data, new div is created as per JS logic written in file. But my earlier inputs to animalName0 & animalType0 becomes empty & I have to insert data there all over again.

Can you please help here?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The problem is the line form.innerHTML+=html is shorthand for form.innerHTML = form.innerHTML + html. When it grabs the form.innerHTML to add to the html it is grabbing the HTML only. Text typed into inputs are not a part of the HTML. Then when you set the innerHTML, think form.innerHTML = form.innerHTML + html, brand new HTML elements are created based off of the HTML only. Any state, including typed in text, is lost. Any event listeners will also be lost in this process.

The proper way of adding a new element while leaving any adjacent elements in place is to create the new element with document.createElement, and add it with a function like .appendChild, like so

var counter = 0
function add_more_animals() {
    counter+=1;

    // Create an empty element
    const newEl = document.createElement('div')
    newEl.id = `catalogue${counter}`

    // Add the first input
    const nameInput = document.createElement('input')
    nameInput.name = `animalName${counter}`
    newEl.appendChild(nameInput)

    // Now the second one
    const typeInput = document.createElement('input')
    typeInput.name = `animalType${counter}`
    newEl.appendChild(typeInput)

    // And finally attach everything to the animals form
    document.getElementById("animals").appendChild(newEl)
}
<div id="animals">
        <div id="animal0">
            <input type="text" name="animalName0">
            <input type="text" name="animalType0">
        </div>
</div>
<button type="button" onclick="add_more_animals()">Add animals (+)</button>

As you can imagine, this can become verbose if you have a large amount of HTML to add. To make this process easier they came out with template tags which you may prefer using. Use them either like this or like this.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda