JavaScript Code Snippets

Below are some useful JavaScript code snippets for use in everyday projects.

Here is an example of how to generate a random number between two values, in this case 1 and 59, then display it.

var min = 1;
var max = 59;
var randomNumber = Math.floor(Math.random() * (max - min + 1) + min);

document.write(randomNumber);

Here, a random password is generated from a specified set of characters. The length of the password is also randomly selected from a given minimum and maximum length.

// Possible characters in password.
var alpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
var numbers = '0123456789';
var nonAlpha = '{]+-[*=@:)}$^%;(_!&#?>/|.';

// Combine possible password characters into one string.
var charSet = alpha + numbers + nonAlpha;

// Minimum and maximum password length.
var minLength = 20;
var maxLength = 30;

// Select a random password length between the minimum and maximum.
var length = Math.floor(Math.random() * (maxLength - minLength + 1) + minLength);

// variable for new password.
var result = "";

// Construct new password.
for (i = 1; i <= length; i++)
{
    
    // Add a randomly selected character to the new password.
    result += charSet[Math.floor(Math.random() * ((charSet.length-1) - 0 + 1) + 0)];

}

// Display the password.
document.write(result);

Below is an example of how to process all elements of a particular type on a page. In this example, a 'for' loop is used to process all of the links on a page, access the 'href' attribute and display it.

for (var i = 0, l=document.links.length; i<l; i++) 
{

   document.write(document.links[i].href + "<br/>");
  
}

The code below takes a value that has been entered into an input item with an 'id' of 'inputSomething' and first checks to see if something has been entered. If something has been entered, examples follow of how to check for a valid boolean, single character, integer and float. It should be noted that a float will parse successfully as an integer, except that it truncates the number at the decimal point. This is why an additional check is made, comparing the parsed version with the non-parsed version.

// Assign the value entered to a variable.
var inputAsString = document.getElementById("inputSomething").value;

// Check if a value has been entered.
if (!inputAsString)
{

    document.write("Nothing has been entered.");

}
else
{

    // Check if the value is a valid boolean.
    if (inputAsString.toLowerCase() == 'true' || inputAsString.toLowerCase() == 'false')
    {
        document.write("'" + inputAsString + "' is a valid boolean." + "<br />");
    }
    else
    {
        document.write("'" + inputAsString + "' is not a valid boolean." + "<br />");
    }
    
    // Check if the value is a single character.
    if (inputAsString.length == 1 && inputAsString.charAt(0))
    {
        document.write("'" + inputAsString + "' is a valid char." + "<br />");
    }
    else
    {
        document.write("'" + inputAsString + "' is not a valid char." + "<br />");
    }
    
    // Check if the value is a valid int.
    if (parseInt(inputAsString) && inputAsString == parseInt(inputAsString))
    {
        document.write("'" + inputAsString + "' is a valid int." + "<br />");
    }
    else
    {
        document.write("'" + inputAsString + "' is not a valid int." + "<br />");
    }
    
    // Check if the value is a valid float.
    if (parseFloat(inputAsString))
    {
        document.write("'" + inputAsString + "' is a valid float." + "<br />");
    }
    else
    {
        document.write("'" + inputAsString + "' is not a valid float." + "<br />");
    }

}