Skip to content
Advertisement

Js – Loop through array to create inputs and values only filling last item input value

I have a div with id=”inputs” on html and the following code on js:

let paises=[
    {pais: "Honduras",scripttag:`<script src="perro loco come baba"> 'cha cha'` },
    {pais: "Chile",scripttag:"perropapa"},
    {pais: "Madagascar",scripttag:"otro"}
]
let inputDiv=document.getElementById("inputs")
for(let p of paises){
    if(p.scripttag){
        inputDiv.innerHTML+=`<input disabled id="` + p.pais + `">`
        let inputPais=document.getElementById(p.pais)
        inputPais.value=p.scripttag
    }
}

If the element of the paises array has a scripttag property, an input is created and value is filled with scripttag content.

Inputs get created properly, the issue is that in the page all the inputs are empty except the last one created (on this case the input with id Madagascar is filled with “otro”)

Advertisement

Answer

Your issue is that you are not creating a new element every time you want to add a new input.

Instead of adding html to divs like that, you can make use of createElement.

let paises=[
    {pais: "Honduras",scripttag:`<script src="perro loco come baba"> 'cha cha'` },
    {pais: "Chile",scripttag:"perropapa"},
    {pais: "Madagascar",scripttag:"otro"}
]
let inputDiv=document.getElementById("inputs")
for(let p of paises){
    if(p.scripttag){
        const newInput = document.createElement('input')
        newInput.id = p.pais
        newInput.value = p.scripttag
        inputDiv.appendChild(newInput)
    }
}

This way you are adding a new element to the div each loop. Instead of overwriting the previous element. I also think you have more control over the inputs properties using DOM manipulation instead writing everything out in a string and concating.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement