Random Password Generator Using jQuery

Today’s jQuery post is a useful piece of code that you can add onto your registration forms for creating random passwords using only jQuery. The benefit of providing this system is that it generates stronger passwords than most people would create for themselves so offers extra security for critical applications.

The great thing about this function is that it allows us to set both the password length as well as the option to use special characters.

To use this function then we are going to create a form, add a “generate password” link, which will get the random password from the function and insert it into the form and add a second link, which the user clicks if they would like to use the password. If confirmed, we then insert the random password into the password field.

As usual I have used an ordered list for the form structure but obviously you can use whatever style you prefer since its not critical for the password generator. Make sure though that the form has a tag with an id “random”, which we are going to use to display the password.

Give both links the same class name as we will use the same click function for both links. The “confirm” link can be hidden though since we only require this if the “generate” link is clicked. We can do this using CSS as opposed to jQuery:

Now we add the jQuery code that will use the above function to generate and insert the new password:

$(document).ready(function() {
$('.link-password').click(function(e){
// First check which link was clicked
linkId = $(this).attr('id');
if (linkId == 'generate'){
// If the generate link then create the password variable from the generator function
password = $.password(12,true);
// Empty the random tag then append the password and fade In
$('#random').hide().append(password).fadeIn('slow');
// Also fade in the confirm link
$('#confirm').fadeIn('slow');
} else {
// If the confirm link is clicked then input the password into our form field
$('#input-password').val(password);
// remove password from the random tag
$('#random').empty();
// Hide the confirm link again
$(this).hide();
}
e.preventDefault();
});
});

The function is fairly simple. The hide() and fadeIn() isnt essential – you can just append the new password to the #random selector but we added the fadeIn to make it a little more ‘exciting’!

The final e.preventDefault() stops the browser jumping to the top of the screen when the generate and confirm links are clicked.

To change the password length set the first option in the password function to the required number of characters. The second option takes a boolean value and sets whether special characters are to be used in the password.