create unique id with javascript

234,622

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);
}
Share:
234,622
JamesTBennett
Author by

JamesTBennett

Updated on July 08, 2022

Comments

  • JamesTBennett
    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
    JamesTBennett almost 14 years
    How do I insert the <option></option> tag into the select with this?
  • James P.
    James P. almost 12 years
    Unless mistaken that would only check for a duplicate once ?
  • Luca
    Luca over 11 years
    You may want to explain your answer for the benefit of the OP
  • user699242
    user699242 over 11 years
    What's the possibility that you would generate the same ID with this example? Seems possible, but highly unlikely.
  • Nisk
    Nisk about 11 years
    considering the RNG in javascript is shite, it's more likely than you think.
  • Nisk
    Nisk about 11 years
    For 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
    fedeghe almost 11 years
    seem not a good idea (+new Date + +new Date )/2 === +new Date;
  • Michael
    Michael over 10 years
    will fail if you coincidentally happen to have an element with the next id in line already on the page.
  • Michael Paulukonis
    Michael Paulukonis over 9 years
    it's not checking for a duplicate, its incrementing the last numerical value.
  • fedeghe
    fedeghe almost 9 years
    although remote the probability of collision is not null
  • Max Lynn
    Max Lynn over 8 years
    What happens if the user creates the ID in a different country?\
  • Yanick Rochon
    Yanick Rochon over 8 years
    By the way, is you set your initial uniqueId right away, you won't need the condition.
  • Adam Pietrasiak
    Adam Pietrasiak about 8 years
    IT 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
    Brad Lee almost 8 years
    Note 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
    Burak Tokak almost 8 years
    This function has a chance to generate the same id, but +1 for dom "friendlyness"
  • Mark N Hopgood
    Mark N Hopgood over 7 years
    Thank 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
    Ulysse BN almost 7 years
    In that case you'd better use performance.now(): performance.now() === performance.now() === false
  • Admin
    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
    Ulysse BN about 6 years
    You should maybe look at Fabio's answer. Or better, generate an id with a random and a time part (like MongoDB objectID).
  • Dilip D
    Dilip D about 4 years
    Please post the answer along with description not only code. it will be useful for user where to change
  • swisswiss
    swisswiss almost 3 years
    be aware it can have different lenghts
  • Ciprian David
    Ciprian David over 2 years
    Actualy 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 with Math.Random() like so: tests[performance.now()+''+Math.Random()]
  • Ulysse BN
    Ulysse BN over 2 years
    @CiprianDavid edited, feel free to improve if that doesn't feel suitable
  • T'lash
    T'lash about 2 years
    Your 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
    James Newton about 2 years
    Consider adding Math.random as in the Matthias H. answer.
  • Kumar Aditya Mohta
    Kumar Aditya Mohta about 2 years
    Nice 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)