create unique id with javascript
Solution 1
could you not just keep a running index?
var _selectIndex = 0;
...code...
var newSelectBox = document.createElement("select");
newSelectBox.setAttribute("id","select-"+_selectIndex++);
EDIT
Upon further consideration, you may actually prefer to use array-style names for your selects...
e.g.
<select name="city[]"><option ..../></select>
<select name="city[]"><option ..../></select>
<select name="city[]"><option ..../></select>
then, on the server side in php for example:
$cities = $_POST['city']; //array of option values from selects
EDIT 2 In response to OP comment
Dynamically creating options using DOM methods can be done as follows:
var newSelectBox = document.createElement("select");
newSelectBox.setAttribute("id","select-"+_selectIndex++);
var city = null,city_opt=null;
for (var i=0, len=cities.length; i< len; i++) {
city = cities[i];
var city_opt = document.createElement("option");
city_opt.setAttribute("value",city);
city_opt.appendChild(document.createTextNode(city));
newSelectBox.appendChild(city_opt);
}
document.getElementById("example_element").appendChild(newSelectBox);
assuming that the cities
array already exists
Alternatively you could use the innerHTML method.....
var newSelectBox = document.createElement("select");
newSelectBox.setAttribute("id","select-"+_selectIndex++);
document.getElementById("example_element").appendChild(newSelectBox);
var city = null,htmlStr="";
for (var i=0, len=cities.length; i< len; i++) {
city = cities[i];
htmlStr += "<option value='" + city + "'>" + city + "</option>";
}
newSelectBox.innerHTML = htmlStr;
Solution 2
var id = "id" + Math.random().toString(16).slice(2)
Solution 3
another way it to use the millisecond timer:
var uniq = 'id' + (new Date()).getTime();
Solution 4
const uid = function(){
return Date.now().toString(36) + Math.random().toString(36).substr(2);
}
This Function generates very unique IDs that are sorted by its generated Date. Also useable for IDs in Databases.
Solution 5
function uniqueid(){
// always start with a letter (for DOM friendlyness)
var idstr=String.fromCharCode(Math.floor((Math.random()*25)+65));
do {
// between numbers and characters (48 is 0 and 90 is Z (42-48 = 90)
var ascicode=Math.floor((Math.random()*42)+48);
if (ascicode<58 || ascicode>64){
// exclude all chars between : (58) and @ (64)
idstr+=String.fromCharCode(ascicode);
}
} while (idstr.length<32);
return (idstr);
}
JamesTBennett
Updated on July 08, 2022Comments
-
JamesTBennett almost 2 years
I have a form where a user can add multiple select boxes for multiple cities. The problem is that each newly generated select box needs to have a unique id. Can this be done is JavaScript?
UPDATE: here is the part of the form for selecting cities. Also note that i'm using some php to fill in the cities when a specific state is selected.
<form id="form" name="form" method="post" action="citySelect.php"> <select id="state" name="state" onchange="getCity()"> <option></option> <option value="1">cali</option> <option value="2">arizona</option> <option value="3">texas</option> </select> <select id="city" name="city" style="width:100px"> </select> <br/> </form>
Here is the javascript:
$("#bt").click(function() { $("#form").append( "<select id='state' name='state' onchange='getCity()'> <option></option> <option value='1'>cali</option> <option value='2'>arizona</option> <option value='3'>texas</option> </select> <select id='city' name='city' style='width:100px'></select><br/>" ); });
-
JamesTBennett almost 14 yearsHow do I insert the <option></option> tag into the select with this?
-
James P. almost 12 yearsUnless mistaken that would only check for a duplicate once ?
-
Luca over 11 yearsYou may want to explain your answer for the benefit of the OP
-
user699242 over 11 yearsWhat's the possibility that you would generate the same ID with this example? Seems possible, but highly unlikely.
-
Nisk about 11 yearsconsidering the RNG in javascript is shite, it's more likely than you think.
-
Nisk about 11 yearsFor a laugh I decided to see how likely it is: var meh=fun();while(meh !== fun()){ console.log('.'); } in Chrome's command line...so far it's a million in with no duplicates, for most cases you can have that's more than enough. To be expected with 32 char length I guess.
-
fedeghe almost 11 yearsseem not a good idea
(+new Date + +new Date )/2 === +new Date;
-
Michael over 10 yearswill fail if you coincidentally happen to have an element with the next id in line already on the page.
-
Michael Paulukonis over 9 yearsit's not checking for a duplicate, its incrementing the last numerical value.
-
fedeghe almost 9 yearsalthough remote the probability of collision is not null
-
Max Lynn over 8 yearsWhat happens if the user creates the ID in a different country?\
-
Yanick Rochon over 8 yearsBy the way, is you set your initial
uniqueId
right away, you won't need the condition. -
Adam Pietrasiak about 8 yearsIT WILL NOT BE UNIQUE if you'll create 2 id's one after another.
var first = (new Date()).getTime(); var second = (new Date()).getTime(); console.log(first == second);
-
Brad Lee almost 8 yearsNote that using a running counter can lead to extremely likely collisions between page hits. In other words, if the counter starts at 1 every time the page loads, then it's likely you will collide the next time you edit/update the object. Good to keep that in mind.
-
Burak Tokak almost 8 yearsThis function has a chance to generate the same id, but +1 for dom "friendlyness"
-
Mark N Hopgood over 7 yearsThank you - here's how I modified for my use. I reused the code, replacing the letter line with var IdStr = ''; Then I set the idStrLen to 16 to give me a sortable (time) id such as: ivm859mg_9dl74lu
-
Ulysse BN almost 7 yearsIn that case you'd better use
performance.now()
:performance.now() === performance.now() === false
-
Admin about 6 years@UlysseBN Just tried
performance.now()
and it does not work as you describe on my machine, despite the ultra-high resolution. -
Ulysse BN about 6 yearsYou should maybe look at Fabio's answer. Or better, generate an id with a random and a time part (like MongoDB objectID).
-
Dilip D about 4 yearsPlease post the answer along with description not only code. it will be useful for user where to change
-
swisswiss almost 3 yearsbe aware it can have different lenghts
-
Ciprian David over 2 yearsActualy I get duplicates using this method! eg:
var tests = {}; var test = function(){tests[performance.now()]=arguments[0]}; test(1);test(2);test(3);test(4);test(5);test(6);test(7);test(8);test(9);test(10);console.log(Object.keys(tests).length);//expected 10 but there is less than that
you must use it in conjunction withMath.Random()
like so:tests[performance.now()+''+Math.Random()]
-
Ulysse BN over 2 years@CiprianDavid edited, feel free to improve if that doesn't feel suitable
-
T'lash about 2 yearsYour test is not a proof as the result will always be 0 because ids.indexOf(el) and ids.indexOf(ell) are always the same value.
-
James Newton about 2 yearsConsider adding Math.random as in the Matthias H. answer.
-
Kumar Aditya Mohta about 2 yearsNice one, maybe a slight change to make the length fixed:
Date.now().toString(36) + Math.floor(Math.pow(10, 12) + Math.random() * 9*Math.pow(10, 12)).toString(36)