PDA

View Full Version : Autogenerate form fields with random text



nyckidd
05-11-2011, 02:01 PM
I have a registration form and i want to autogenerate one of the text fields with random numbers or letters , basically when user gets to the page the field is hidden but it will populate with random numbers or text...

midhul
05-11-2011, 05:00 PM
There are millions of ways of generating random strings.
You can use the Math.random(); function:




function randomString(length) {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split('');

if (! length) {
length = Math.floor(Math.random() * chars.length);
}

var str = '';
for (var i = 0; i < length; i++) {
str += chars[Math.floor(Math.random() * chars.length)];
}
return str;
}




Now assuming you have a hidden input as you mentioned:



<input id="secret" type="hidden">


Simply use DOM + our random function:



document.getElementById("secret").value = randomString(16);

jscheuer1
05-12-2011, 08:59 AM
Do you really want random? That serves no useful purpose I can think of. You might be going for unique. If so, you could use only numbers and the date object:


document.getElementById("secret").value = new Date().getTime());