95

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/>"
     );
});
Cloud
  • 944
  • 1
  • 15
  • 45
JamesTBennett
  • 1,742
  • 5
  • 16
  • 22
  • Are you using a framework/toolkit like Jquery or just vanilla js? Also, can you post some of your code, at least the generated html output? – DeaconDesperado Jul 12 '10 at 19:15
  • You may be better off using radio buttons for this kind of behaviour. Otherwise in Javascript you can come up with a name like 'cities' then using an iterator like 'var i = 0;' for each select box do .setAttribute('id', 'cities' + i). getElementsByTagName('?') will help here. You'll need to provide some sample HTML for someone to really help. – Metalshark Jul 12 '10 at 19:16
  • 1
    Are you asking about generating a unique id attribute for each new ? You can, in javascript, maintain a reference to the specific new DOM element, rather than just its id. So, you don't have to generate a unique ID, depending on what you're trying to do. – pioto Jul 12 '10 at 19:17
  • 1
    I believe he's saying that they can list one or more cities, each coming from a select – Jonathan Fingland Jul 12 '10 at 19:19
  • You can see the answer for the same [here](http://stackoverflow.com/questions/3782825/how-to-add-unique-id-to-dynamically-generated-inputs/37424649#37424649) – Sanjay Nishad May 24 '16 at 22:06

29 Answers29

80
var id = "id" + Math.random().toString(16).slice(2)
Fabio Montefuscolo
  • 1,728
  • 1
  • 17
  • 18
65

another way it to use the millisecond timer:

var uniq = 'id' + (new Date()).getTime();
Scott Evernden
  • 37,365
  • 14
  • 77
  • 84
  • 4
    seem not a good idea `(+new Date + +new Date )/2 === +new Date;` – fedeghe Jul 17 '13 at 12:58
  • 4
    What happens if the user creates the ID in a different country?\ – Max Lynn Jan 08 '16 at 09:46
  • 24
    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);` – Adam Pietrasiak Apr 06 '16 at 21:32
  • 1
    In that case you'd better use `performance.now()`: `performance.now() === performance.now() === false` – Ulysse BN Aug 17 '17 at 18:40
  • 2
    @UlysseBN Just tried `performance.now()` and it does not work as you describe on my machine, despite the ultra-high resolution. –  May 14 '18 at 12:46
  • You should maybe look at Fabio's answer. Or better, generate an id with a random and a time part (like MongoDB objectID). – Ulysse BN May 14 '18 at 12:57
  • Consider adding Math.random as in the Matthias H. answer. – James Newton May 29 '22 at 04:51
57
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.

Matthias H.
  • 571
  • 4
  • 2
36

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;
Jonathan Fingland
  • 54,815
  • 11
  • 82
  • 78
  • 1
    How do I insert the tag into the select with this? – JamesTBennett Jul 12 '10 at 21:24
  • 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. – Brad Lee Jul 20 '16 at 19:31
24
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);
}
Guy Thomas
  • 241
  • 2
  • 2
  • 2
    You may want to explain your answer for the benefit of the OP – Luca Oct 20 '12 at 01:17
  • What's the possibility that you would generate the same ID with this example? Seems possible, but highly unlikely. – user699242 Oct 23 '12 at 20:03
  • 1
    considering the RNG in javascript is shite, it's more likely than you think. – Nisk May 20 '13 at 15:23
  • 2
    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. – Nisk May 20 '13 at 15:32
  • This function has a chance to generate the same id, but +1 for dom "friendlyness" – Burak Tokak Aug 26 '16 at 13:06
13

No external libraries needed. Uniqueness proved.

You could do something like this.

// Function to generate unique id

const uniqueId = (length=16) => {
  return parseInt(Math.ceil(Math.random() * Date.now()).toPrecision(length).toString().replace(".", ""))
}

// ----------------------------

document.querySelector("#butt01").onclick = () => {
  document.querySelector("#span01").innerHTML = uniqueId()
}

ids = []
count = 0
document.querySelector("#butt02").onclick = () => {
  for (let i = 0; i< 1000; i++){
    ids.push(uniqueId())
  }
  for (el of ids){
    for (ell of ids){
      if(el == ell && ids.indexOf(el) != ids.indexOf(ell)){
        count += 1
      }
    }
  }
  document.querySelector("#span02").innerHTML = `Found ${count} duplicated random values.`
}
<button id="butt01">Generate</button>
<br>
<span id="span01"></span>
<br>
<hr>
<br>
<button id="butt02">Check collision potentiality in 1000 cases</button>
<br>
<span id="span02"></span>

Multiply time in milliseconds since epoch with a random value to fixed size.

Run this to see possible collisions.

You would see there are no collisions whether it is 1000, 10000 or 1000000000.

It would have a very small chance if two users generate ids at the same time and gets the rame random number.

To increase the uniqueness you could multiply date more Math.random()s.

Cliffniff
  • 372
  • 4
  • 12
  • 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. – T'lash May 19 '22 at 19:28
11

Very short function will give you unique ID:

var uid = (function(){var id=0;return function(){if(arguments[0]===0)id=0;return id++;}})();

alert ( uid() );

Junaid Atari
  • 525
  • 7
  • 17
  • 3
    will fail if you coincidentally happen to have an element with the next id in line already on the page. – Michael Mar 03 '14 at 22:45
10

You could generate an ID using a timer and avoiding duplicates using performance.now():

id = 'id' + performance.now()
dup = 'id' + performance.now()

console.log(id)
console.log(id.replace('.','')) // sexy id
console.log(id === dup) // false!
.as-console-wrapper{border-top: none !important;overflow-y: auto !important;top: 0;}

Note that the High resolution time API is available in all recent browsers.


EDIT(per Ciprian's comment): That is unfortunately not enough, performance.now() is only precise to the millisecond. Consider using it in conjuction with Math.random():

const generateId = () => `${performance.now()}${Math.random().toString().slice(5)}`.replace('.','')

let id = generateId()
let dup = generateId()

console.log(id)
console.log(id === dup) // false!

let ary = [...Array(1000)].map(_ => generateId())
console.log((new Set(ary)).size === 1000) // no dups!
.as-console-wrapper{border-top: none !important;overflow-y: auto !important;top: 0;}
Ulysse BN
  • 8,503
  • 5
  • 45
  • 74
  • 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()]` – Ciprian David Jan 09 '22 at 08:08
  • @CiprianDavid edited, feel free to improve if that doesn't feel suitable – Ulysse BN Jan 09 '22 at 11:23
9

In reply to @scott : Sometime JS go very fast... so...

var uniqueId = null,
    getUniqueName = function(prefix) {
        if (!uniqueId) uniqueId = (new Date()).getTime();
        return (prefix || 'id') + (uniqueId++);
    };
molokoloco
  • 4,286
  • 2
  • 31
  • 27
8

I'm working on a similar problem to the OP, and found that elements of the solutions from @Guy and @Scott can be combined to create a solution that's more solid IMO. The resulting unique id here has three sections separated by underscores:

  1. A leading letter;
  2. A timestamp displayed in base 36;
  3. And a final, random section.

This solution should work really well, even for very large sets:

function uniqueId () {
    // desired length of Id
    var idStrLen = 32;
    // always start with a letter -- base 36 makes for a nice shortcut
    var idStr = (Math.floor((Math.random() * 25)) + 10).toString(36) + "_";
    // add a timestamp in milliseconds (base 36 again) as the base
    idStr += (new Date()).getTime().toString(36) + "_";
    // similar to above, complete the Id using random, alphanumeric characters
    do {
        idStr += (Math.floor((Math.random() * 35))).toString(36);
    } while (idStr.length < idStrLen);

    return (idStr);
}
yodarunamok
  • 423
  • 5
  • 8
  • 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 – Mark N Hopgood Nov 17 '16 at 10:43
7

put in your namespace an instance similar to the following one

var myns = {/*.....*/};
myns.uid = new function () {
    var u = 0;
    this.toString = function () {
        return 'myID_' + u++;
    };
};
console.dir([myns.uid, myns.uid, myns.uid]);
fedeghe
  • 1,157
  • 11
  • 21
4

You can use the Generator function, was introduced in ES6 (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*)

const idCreator = function* () {
    let i = 0;
    while (true) yield i++;
};

const idsGenerator = idCreator();
const generateId = () => idsGenerator.next().value;

console.log(generateId()) // 0
console.log(generateId()) // 1
console.log(generateId()) // 2
...
Asaf
  • 503
  • 5
  • 11
3

To avoid creating any counters and be sure that the id is unique even if there are some other components that create elements with ids on the page, you can use a random number and than correct it if it's not good enough (but you also have to set the id immediately to avoid conflicts):

var id = "item"+(new Date()).getMilliseconds()+Math.floor(Math.random()*1000);
 // or use any random number generator
 // whatever prefix can be used instead of "item"
while(document.getElementById(id))
    id += 1;
//# set id right here so that no element can get that id between the check and setting it
YakovL
  • 6,451
  • 11
  • 52
  • 82
2

Random is not unique. Times values are not unique. The concepts are quite different and the difference rears its ugly head when your application scales and is distributed. Many of the answers above are potentially dangerous.

A safer approach to the poster's question is UUIDs: Create GUID / UUID in JavaScript?

javajon
  • 1,515
  • 15
  • 18
2

There are two packages available for this.

  • For short unique id generation nanoid link
import { nanoid } from 'nanoid'
const id = nanoid()    // "Uakgb_J5m9g-0JDMbcJqLJ"
const id = nanoid(10)  // "jcNqc0UAWK"
  • For universally unique id generation uuid link
import { v4 as uuidv4 } from 'uuid';
const id= uuidv4();    // quite big id
Dharman
  • 26,923
  • 21
  • 73
  • 125
shivampip
  • 1,666
  • 17
  • 16
1

Like others said you can use a running index, or if you don't like the idea of using a variable just pull the id of the last city in the list and add 1 to its id.

qw3n
  • 5,966
  • 6
  • 31
  • 59
1

Here is a function (function genID() below) that recursively checks the DOM for uniqueness based on whatever id prefex/ID you want.

In your case you'd might use it as such

var seedNum = 1;
newSelectBox.setAttribute("id",genID('state-',seedNum));

function genID(myKey, seedNum){
     var key = myKey + seedNum;
     if (document.getElementById(key) != null){
         return genID(myKey, ++seedNum);
     }
     else{
         return key;
     }
 }
Bob Sheehan
  • 160
  • 1
  • 6
1

Warning: This answer may not be good for the general intent of this question, but I post it here nevertheless, because it solves a partial version of this issue.

You can use lodash's uniqueId (documentation here). This is not a good uniqueId generator for say, db records, or things that will persist a session in a browser or something like that. But the reason I came here looking for this was solved by using it. If you need a unique id for something transient enough, this will do.

I needed it because I was creating a reusable react component that features a label and a form control. The label needs to have a for="controlId" attribute, corresponding to the id="controlId" that the actual form control has (the input or select element). This id is not necessary out of this context, but I need to generate one id for both attributes to share, and make sure this id is unique in the context of the page being rendered. So lodash's function worked just fine. Just in case is useful for someone else.

Ernesto
  • 3,677
  • 5
  • 33
  • 51
1
function generateId() {
       
  return Math.random().toString(36).substring(2) +
    (new Date()).getTime().toString(36);
}

console.log(generateId())
YakovL
  • 6,451
  • 11
  • 52
  • 82
  • 1
    Please post the answer along with description not only code. it will be useful for user where to change – Dilip D Jul 01 '20 at 10:44
1

Look at this functions, it will get ur job done.

If u want uppercase and lowercase chars in ur string:

function (length) {
    var id = '';
            while (id.length < length) {
                var ch = Math.random()
                    .toString(36)
                    .substr(2, 1);
                if (Math.random() < 0.5) {
                    ch = ch.toUpperCase();
                }
                id += ch;
            }
            return id;
}

Only lowercase chars:

function (length) {
    var id = '';
            while (id.length < length) {
                id += Math.random()
                    .toString(36)
                    .substr(2, 1);
            }
            return id;
}
smarteist
  • 1,112
  • 11
  • 13
1

Simple Solution :)

const ID = (_length=13) => {
  // Math.random to base 36 (numbers, letters),
  // grab the first 9 characters
  // after the decimal.
  return '_' + Math.random().toString(36).substr(2, _length); // max _length should be less then 13
};
console.log("Example ID()::", ID())
dipenparmar12
  • 2,318
  • 1
  • 25
  • 34
0

Here's my own take at it based on the xpath of the element created :

/** Returns the XPATH of an element **/
var getPathTo = function(element) {
  if (element===document.body)
      return element.tagName;

  var ix= 0;
  var siblings= element.parentNode.childNodes;
  for (var i= 0; i<siblings.length; i++) {
      var sibling= siblings[i];
      if (sibling===element)
          // stripped xpath (parent xpath + tagname + index)
          return getPathTo(element.parentNode)+ element.tagName + ix+1;
      if (sibling.nodeType===1 && sibling.tagName===element.tagName)
          ix++;
   }
}

/** hashcode function (credit http://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript-jquery **/
var hashCode = function(str) {
  var hash = 0, i, chr, len;
  if (str.length === 0) return hash;
  for (i = 0, len = str.length; i < len; i++) {
    chr   = str.charCodeAt(i);
    hash  = ((hash << 5) - hash) + chr;
    hash |= 0; // Convert to 32bit integer
 }
return hash;
};

/** Genaretes according to xpath + timestamp **/
var generateUID = function(ele)
{
  return hashCode(getPathTo(ele)) + new Date().getTime();
}

First the xpath of the element is fetched.

The hashcode of the xpath is then computed. We therefore have a unique id per xpath.

The problem here is that xpath are not necesseraly unique if unique elements are generated on the fly. Thus we add the timestamp at the end.

Maybe we could also garantee more unique elements by adding a final Math.Random().

Laurent B
  • 2,142
  • 17
  • 29
0

You could take advantage of closure.

var i = 0;
function generateId() {
    return i++;
}

If you want to enclose it:

function generator() {
  var i = 0;
  return function() {
    return i++;
  };
}

var generateId = generator();
generateId(); //1
generateId(); //2

generator could accept a default prefix; generateId coud accept an optional suffix:

function generator(prefix) {
  var i = 0;
  return function(suffix) {
    return prefix + (i++) + (suffix || '');
  };
}

var generateId = generator('_');
generateId('_'); //_1_
generateId('@'); //_2@

This comes in handy if you want your id to indicate a sequence, very much like new Date().getTime(), but easier to read.

roland
  • 7,395
  • 6
  • 45
  • 60
0

Combining random & date in ms should do the trick with almost no change of collision :

function uniqid(){
  return Math.random().toString(16).slice(2)+(new Date()).getTime()+Math.random().toString(16).slice(2);
}
alert(uniqid()+"\r"+uniqid());
Bibou
  • 124
  • 4
0
    const generateUniqueId = () => 'id_' + Date.now() + String(Math.random()).substr(2);

    // if u want to check for collision
    const arr = [];
    const checkForCollision = () => {
      for (let i = 0; i < 10000; i++) {
        const el = generateUniqueId();
        if (arr.indexOf(el) > -1) {
          alert('COLLISION FOUND');
        }
        arr.push(el);
      }
    };
Artem Bochkarev
  • 1,002
  • 11
  • 19
0

I think if you really want to have a unique ID then the best approach is to use a library like:
uuid or uniqueid

Note: Unique ID is not the same as Random ID

To use only date time milliseconds approach is wrong.
Nowadays computers are fast enough and able to run more than one iteration of a loop in a single millisecond.

npm install uuid

Importing the library:

If you are using ES modules

import { v4 as uuidv4 } from 'uuid';

And for CommonJS:

const { v4: uuidv4 } = require('uuid');

Usage:

uuidv4();

// This will output something like: 9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d
V. Sambor
  • 10,295
  • 5
  • 42
  • 59
0

For generate unique id's:

const uid = () =>
  String(
    Date.now().toString(32) +
      Math.random().toString(32) +
      Math.random().toString(32)
  ).replace(/\./g, '')

For check that is works:

var size = 500000
var arr = new Array(size)
  .fill(0)
  .map(() => uid())

var b = new Set(arr)

console.log(
  size === b.size ? 'all ids are unique' : `not unique records ${size - b.size}`
)
-1

I use a function like the following:

function (baseId) {
  return baseId + '-' + Math.random().toString(16).slice(2);
}

In parameter baseId I indicate a prefix for the id to be easier to identify the elements.

-1

let transactionId =${new Date().getDate()}${new Date().getHours()}${new Date().getSeconds()}${new Date().getMilliseconds()}

let transactionId =`${new Date().getDate()}${new Date().getHours()}${new Date().getSeconds()}${new Date().getMilliseconds()}` 

console.log(transactionId)