135

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 in 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/>"
     );
});
5
  • 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? Jul 12, 2010 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, 2010 at 19:16
  • 1
    Are you asking about generating a unique id attribute for each new <option id="blah">New City</option>? 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, 2010 at 19:17
  • 1
    I believe he's saying that they can list one or more cities, each coming from a select Jul 12, 2010 at 19:19
  • You can see the answer for the same here May 24, 2016 at 22:06

35 Answers 35

1
2
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();
console.log(generateId()); //1
console.log(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('_');
console.log(generateId('_')); //_1_
console.log(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.

0

This can be achieved using random dates:

const uniqueId = new Date(Math.ceil(Math.random() * 1e13)).valueOf().toString(36);

// Sample output: '1x7kf3ygb'

or

const unique = window.btoa(new Date(Math.ceil(Math.random() * 1e13)).getTime());

// Sample output: 'MjA5MTQzOTQ4MDk2'
0

Combining random and date in ms should do the trick with almost no chance of collision:

function uniqid(){
  return Math.random().toString(16).slice(2)+(new Date()).getTime()+Math.random().toString(16).slice(2);
}
console.log(uniqid()+"\r"+uniqid());

-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)

1
2

Not the answer you're looking for? Browse other questions tagged or ask your own question.