javascript – generate random string for div id – Stack Overflow

javascript – generate random string for div id – Stack Overflow

Not sure what your problem is, but a way simpler way to create a unique ID in JavaScript is to use the Date object:

var uniqid = Date.now();

That gives you the total milliseconds elapsed since January 1st 1970, which is a unique value every time you call that.

The problem with that value now is that you cannot use it as an element’s ID, since in HTML, IDs need to start with an alphabetical character. There is also the problem that two users doing an action at the exact same time might result in the same ID. We could lessen the probability of that, and fix our alphabetical character problem, by appending a random letter before the numerical part of the ID.

var randLetter = String.fromCharCode(65 + Math.floor(Math.random() * 26));

var uniqid = randLetter + Date.now();

This still has a chance, however slim, of colliding though. Your best bet for a unique id is to keep a running count, increment it every time, and do all that in a single place, ie, on the server.

via javascript – generate random string for div id – Stack Overflow.

Advertisements
php – Generating random but unique numbers for reference ID – Stack Overflow

php – Generating random but unique numbers for reference ID – Stack Overflow

Why not just preface your random number with a Unix timestamp? This will ensure uniqueness.

$random = time() . rand(10*45, 100*98);

Otherwise, you can store your numbers in a file. If you can, store them in a database.

via php – Generating random but unique numbers for reference ID – Stack Overflow.