Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

144
Views
Agregue una identificación aleatoria para múltiples <input>

Tengo un problema, creé un generador de formulario, el usuario agrega varios campos y me gustaría en JavaScript poder modificar la identificación y hacerla única para la recuperación de datos.

En mi función hice esto pero la identificación se modifica solo para el primer campo...:

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

Tengo esto:

 <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=""/>

y me gustaría tener por ejemplo algo como esto:

 <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 answers
Answer question

0

Debe usar document.querySelectorAll o document.getElementsByClassName para obtener la lista de elementos para poder actualizar la id de esos, ya document.getElementById devuelve un solo elemento (el primer elemento que coincide con la identificación):

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

O con bucle for simple:

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!