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

158
Visualizações
Add a random id for multiple <input>

I have a problem, I created a builder for form, the user adds several fields and I would like in JavaScript to be able to modify the id and make it unique for the data recovery.

In my function I did this but the id is modified only for the first field...:

let id = () => {
        return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
    }
    document.getElementById("changeInput").id = "changeInput" + id();

I have this:

<input class="build-element" id="changeInput" placeholder="Some text" value=""/>
<input class="build-element" id="changeInput" placeholder="Some text" value=""/>
<input class="build-element" id="changeInput" placeholder="Some text" value=""/>

and I would like to have for example something like this:

<input class="build-element" id="changeInput1" placeholder="Some text" value=""/>
<input class="build-element" id="changeInput2" placeholder="Some text" value=""/>
<input class="build-element" id="changeInput3" placeholder="Some text" value=""/>
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You need to use document.querySelectorAll or document.getElementsByClassName to get the list of elements to be able to update id of those, since document.getElementById returns a single element (the first element that matches the id) :

Array.from(document.querySelectorAll(".build-element")).forEach((element) => {
  element.id = "changeInput" + id();
});

Or with simple for loop :

const elements = document.querySelectorAll(".build-element");
for(let i=0; i<elements.length; i++) {
 elements[i].id = "changeInput" + id();
}
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