Add a random id for multiple <input>

Viewed 107

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

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();
}
Related