2

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?

1 Answers1

1

The problem stems from the line form.innerHTML+=html which is shorthand for form.innerHTML = form.innerHTML + html. When it gets the form.innerHTML it is grabbing the HTML only; The text typed into the inputs are not a part of this HTML. When the innerHTML gets set, think form.innerHTML = form.innerHTML + html, brand new HTML elements are created based off of the HTML only, and 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 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.

hostingutilities.com
  • 8,894
  • 3
  • 41
  • 51