jQuery Javascript create unique ID for an Element

Hi Guys,

There are time when you want to create a unique ID on the Fly either from your JQuery plugin or your usual JavaScript Code

Here are couple of ways I use without extending the Object class

First method

  1. function uniqID(idlength) {
  2. var charstoformid = '_0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split('');
  3. if (! idlength) {
  4. idlength = Math.floor(Math.random() * charstoformid.length);
  5. }
  6. var uniqid = '';
  7. for (var i = 0; i < length; i++) {
  8. uniqid += charstoformid[Math.floor(Math.random() * charstoformid.length)];
  9. }
  10. // one last step is to check if this ID is already taken by an element before
  11. if(jQuery("#"+uniqid).length == 0)
  12. return uniqid;
  13. else
  14. return uniqID(20)
  15. }

Usage

You can use the above method to return uniq id as shown below

  1. var uniq_id = uniqID(20);

Second method

In second method we will use a counter as shown below

  1. var uniqID = {
  2. counter:0,
  3. get:function(prefix) {
  4. if(!prefix) {
  5. prefix = "uniqid";
  6. }
  7. var id = prefix+""+uniqID.counter++;
  8. if(jQuery("#"+id).length == 0)
  9. return id;
  10. else
  11. return uniqID.get()
  12.  
  13. }
  14. }

Above method use an object with has one property counter and a method get

Usage

Above can be utilized in your code as shown below

  1. var uniq_id = uniqID.get();
  2. // if you want to prefix your ID the do this
  3. var uniq_id = uniqID.get('myprefix')

I have typed above code directly in this post rather than copy pasting

If you find any error in above method or want to suggest any other method please leave your comments.

Cheers,

 

 

 

 

 

VN:F [1.9.22_1171]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Speak Your Mind

*

CommentLuv badge