PDA

View Full Version : random alphanumeric string in form field

jaggedgenius
10-12-2011, 10:00 AM
Hello everyone.

I am completely new to javascript and am basically able to copy/paste code with some minor editing.

What I am looking for is a way to have a 5 digit alphanumeric number generated inside a form field to be sent through php(mail).

Any help would be greatly appreciated, and any more information I can give, I will gladly do so.

Kor
10-12-2011, 12:58 PM
5 digit alphanumeric
Alphanumeric is a combination of letters AND digits. So: you need a 5 length characters alphanumeric string? Or a 5 digits number? Are letters and/or digits required?

Logic Ali
10-12-2011, 01:49 PM
If you use PHP wouldn't it be better to do it in PHP?

This function returns a lowercase alphanumeric string of specified length.

<script type="text/javascript">

function randAlnum( len )
{
var str = '',
rv;

do{
str = "";

for( var i = 0; i < len; i++ )
{
rv = Math.floor( Math.random() * 36 );
str += String.fromCharCode( rv + ( rv < 10 ? 48 : 87 ) );
}

}while( !/[a-z]/.test(str) || !/[0-9]/.test(str) );

return str;
}

ippo
10-12-2011, 06:14 PM
Hi Ali,
But what does this code do-

!/[a-z]/.test(str) || !/[0-9]/.test(str)

Is "test" an in-built function?

Can you please explain the logic of the above code? will be greatly benefited :thumbsup:
Also why such a complicated operation to generate a alphanumeric code ?

rv = Math.floor( Math.random() * 36 );
str += String.fromCharCode( rv + ( rv < 10 ? 48 : 87 ) );
I don't understand why you require this codes -
str += String.fromCharCode( rv + ( rv < 10 ? 48 : 87 ) );
Can you plz explain? :)

Logic Ali
10-12-2011, 07:32 PM
Hi Ali,