jQuery: generate a random password

The word "random" should not be taken literally when it comes to JavaScript. However, in the following example I've tried to reproduce the basic routine of many similar PHP functions, though the final result doesn't take into account the removal of character duplicates. So I've created a basic jQuery global function to perform this task. Let's see how.

Here's the function:

(function($) {

  $.generateRandomPassword = function(limit) {
    limit = limit || 8;
    var password = '';
    var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789:;><!"£$%&/()=?^*°#_-@+[]{}|,.§ç';
    var list = chars.split('');
    var len = list.length, i = 0;
    do {
      var index = Math.floor(Math.random() * len);
      password += list[index];
    } while(i < limit);
    return password;


You can set a limit to this function in order to get the desired password length. Here's an example:

$(function() {

  $('#generate').click(function(event) {
    var pwd = $.generateRandomPassword(13);


You can see the demo below.


Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.