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

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

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 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!