Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

156
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda