Software, your way.
burger menu icon
WillMaster

WillMaster > LibraryGenerators and Converters

FREE! Coding tips, tricks, and treasures.

Possibilities weekly ezine

Get the weekly email website developers read:

 

Your email address

name@example.com
YES! Send Possibilities every week!

Random Characters with JavaScript

Random order numbers, passwords, and financial transaction ID's can all benefit from random character generation. And other things requiring random characters.

The random characters may be generated when a page loads to pre-fill a form field or print them directly on the page.

Examples of use: A randomly generated transaction ID printed on a page with an order form the site visitor can print out. A randomly generated order number stored in a cookie and inserted into a hidden form field. A password field on an application form contains a suggested password that was randomly generated.

This article provides a random character string generator in the form of a JavaScript function. The examples show how to publish a random order number on a page and how to pre-fill a form with a password generated on-the-fly.

The random character string generator lets you specify a list of characters to pick from when the generator runs.

To generate a password, it may be desirable to let the function pick from every keyboard character. Because the examples in this article include an order number and both use the same random character string generator, non-alphanumeric characters are omitted, as are these easily misread characters: oO0l1

Specify the list of characters appropriate for your implementation.

The minimum number of characters for the length of the random character string is custom specified. As is the maximum number of characters. To specify an exact length, the minimum and maximum are specified the same.

Below are the working examples mentioned earlier. An order number for a purchase confirmation page and a suggested password for an application form.

When this web page loaded in your browser, the random order number and suggested password were generated. Each is from 8 to 12 characters long.

Order number:

Specify a password:

Implementation

Implementation is in two parts.

  1. The random character string generator, a JavaScript function. This is placed on the web page somewhere above where it will be used.

  2. The code to use the generator.

The Random Character String Generator

Here is the random character string generator, the JavaScript function RandomCharacterStringGenerator().

<script type="text/javascript"><!--
/* 
   Random Character String Generator
   Version 1.0
   January 16, 2012

   Will Bontrager Software, LLC
   https://www.willmaster.com/
   Copyright 2012 Will Bontrager Software, LLC

   This software is provided "AS IS," without 
   any warranty of any kind, without even any 
   implied warranty such as merchantability 
   or fitness for a particular purpose.
   Will Bontrager Software, LLC grants 
   you a royalty free license to use or 
   modify this software provided this 
   notice appears on all copies. 
*/

// Leave next line as is.
function RandomCharacterStringGenerator() {
// Leave above line as is.

//////////////////////////////////////////////////////
//
// Customizations:
//
// Specify the characters to be used when the random character 
//    string generator creates the character string.

var RandomCharsToUse = "abcdefghijkmnpqrstuvwxyz23456789ABCDEFGHJKLMNPQRSTUVWXYZ";

// Specify the minimum number of characters and the maximum 
//    number of characters for the random character string.

var MinimumNumberOfCharacters = 8;
var MaximumNumberOfCharacters = 12;

// No other customization required for this JavaScript
//////////////////////////////////////////////////////
RandomCharsToUse = RandomCharsToUse.replace(/\s/g,"");
MinimumNumberOfCharacters = parseInt(MinimumNumberOfCharacters);
MaximumNumberOfCharacters = parseInt(MaximumNumberOfCharacters);
if( MaximumNumberOfCharacters < MinimumNumberOfCharacters ) { MaximumNumberOfCharacters = MinimumNumberOfCharacters; }
var CharactersLength = RandomCharsToUse.length;
var StringLength = 0;
if( MaximumNumberOfCharacters == MinimumNumberOfCharacters ) { StringLength = MinimumNumberOfCharacters; }
else { StringLength = Math.floor(Math.random()*(MaximumNumberOfCharacters-MinimumNumberOfCharacters+1)) + MinimumNumberOfCharacters; }
var ReturnString = new String();
while( ReturnString.length < StringLength ) { ReturnString += RandomCharsToUse.charAt(Math.floor(Math.random()*CharactersLength)); }
return ReturnString;
}
//--</script>

The function has three places to customize. Each place is marked.

  1. RandomCharsToUse — Specify the characters to pick from when generating a random character string. To make certain characters more likely to be picked, specify them several times and/or omit some others.

  2. MinimumNumberOfCharacters — Specify the minimum number of characters for the random character string.

  3. MaximumNumberOfCharacters — Specify the maximum number of characters for the random character string. To specify an exact length for the random character string, specify the same number for both MinimumNumberOfCharacters and MaximumNumberOfCharacters.

The function RandomCharacterStringGenerator() JavaScript needs to be on the web page somewhere above where it will be called. In the head area of the source code may be a good place for it depending on how your pages are set up.

The RandomCharacterStringGenerator() function may be imported from an external file.

The Example Order Number

A random order number is published by writing the result of calling the RandomCharacterStringGenerator(). Here is the code used in the above example.

<p>
Order number: <script type="text/javascript"><!--
document.write( RandomCharacterStringGenerator() );
//--></script>
</p>

The JavaScript is put in the spot where the order number is to be published. The document.write() function writes the result of the RandomCharacterStringGenerator() call.

The Example Pre-Filled Password Field

Here is the source code for the example field that is pre-filled with a randomly generated password.

<p>
Specify a password: <input type="text" id="transactionIDfield" style="width:125px;">
</p>

<script type="text/javascript"><!--
document.getElementById("transactionIDfield").value = RandomCharacterStringGenerator();
//--></script>

The input field for the password has an id value. The JavaScript below the field uses the id value to insert the random character string from the RandomCharacterStringGenerator() call.

Using the Generator

Put only one instance of the generator in the source code of a page. Even when it is used more than once on the page.

When the RandomCharacterStringGenerator() function is called, it returns a string composed of random characters. That string can be used in any ways a string of characters can be used in JavaScript. In the examples, the string is written to the page and used as a value in a form field.

Will Bontrager

Was this article helpful to you?
(anonymous form)

Support This Website

Some of our support is from people like you who see the value of all that's offered for FREE at this website.

"Yes, let me contribute."

Amount (USD):

Tap to Choose
Contribution
Method

All information in WillMaster Library articles is presented AS-IS.

We only suggest and recommend what we believe is of value. As remuneration for the time and research involved to provide quality links, we generally use affiliate links when we can. Whenever we link to something not our own, you should assume they are affiliate links or that we benefit in some way.

How Can We Help You? balloons
How Can We Help You?
bullet Custom Programming
bullet Ready-Made Software
bullet Technical Support
bullet Possibilities Newsletter
bullet Website "How-To" Info
bullet Useful Information List

© 1998-2001 William and Mari Bontrager
© 2001-2011 Bontrager Connection, LLC
© 2011-2024 Will Bontrager Software LLC