Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create unique id with javascript

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?

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/>"
     );
});
like image 390
JamesTBennett Avatar asked Jul 12 '10 19:07

JamesTBennett


People also ask

What is unique ID in JavaScript?

Introduction to JavaScript UUID. A universally unique identifier (UUID) is an identifier of the 128-bit value that is used in the construction of software. Each bit present in the value differs by the meaning as several variants are considered.

How do you create a unique identifier?

The simplest way to generate identifiers is by a serial number. A steadily increasing number that is assigned to whatever you need to identify next. This is the approached used in most internal databases as well as some commonly encountered public identifiers.

Is date now () unique?

You will do have duplicates if you use only Date. now() in a loop, but Math. random() makes it unique.


3 Answers

var id = "id" + Math.random().toString(16).slice(2) 
like image 120
Fabio Montefuscolo Avatar answered Oct 02 '22 21:10

Fabio Montefuscolo


another way it to use the millisecond timer:

var uniq = 'id' + (new Date()).getTime();
like image 34
Scott Evernden Avatar answered Oct 02 '22 21:10

Scott Evernden


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.

like image 25
Matthias H. Avatar answered Oct 02 '22 21:10

Matthias H.