Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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")

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading