Question

Good morning,

I have this code (just an example):

function random(min, max) {
    return min + parseInt(Math.random() * (max - min + 1));
}
function generatePassword(length, charset) {
    var password = "";
    while (length--) {
        password += charset[random(0, charset.length - 1)];
    }
    return password;
}
function getNewPassword() {
    $('#password').text(generatePassword(12, "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789!?#@*&.,;:+-=()[]_"));
}

And would like to add an input field in HTML, where I can set the length of the generated password.

Can you please find with me a solution? :-)

http://jsfiddle.net/RnsTq/

Was it helpful?

Solution 2

There you have it: http://jsbin.com/odosoy/94/edit

Javascript

$(document).ready(function() {
  $("#generate").click(function() {
    getNewPassword();
  });

  function random(min, max) {
    return min + parseInt(Math.random() * (max - min + 1), 10);
  }
  function generatePassword(charset) {
    var length = parseInt($("#passlength").val(), 10);
    var password = "";
    while (length--) {
      password += charset[random(0, charset.length - 1)];
    }
    return password;
  }
  function getNewPassword() {
    var pass = generatePassword("AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789!?#@*&.,;:+-=()[]_");
    $('#password').val(pass);
  }
});

HTML

Length: <input id="passlength"/><br>
Password: <input id="password"/><br>
<button class="btn btn-info" id="generate">Generate Password</button>

Update

Just reworked and styled your initial example a bit, nothing really special. http://jsbin.com/odosoy/97/edit and one in which the password is replaced: http://jsbin.com/odosoy/125/edit

Hope it helps.

OTHER TIPS

Instead of the 12 in the call to generatePassword use parseInt($('#len').val(), 10), where len would be the id of the input element.

look at this:

function gen_random(len){
    var charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    var tempChar = charset.split('');
    for (var i = 0; i < len; ++i) {
        password += tempChar[Math.floor(Math.random() * (26+26+10)) + 1];           
    }
    return password;    
}

Try to add a new text field and take it's value before you generate your password.

var passwordLength = $('#maxLength').val(); $('#password').val(generatePassword(passwordLength, "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789!?#@*&.,;:+-=()[]_"));

You can see a quick & dirty fiddle here: http://jsfiddle.net/nininho/pG5A7/1/

Try something like this:-

Math.random().toString(36).substring(7);

The best way to generate a password in JS is to use a lib such as https://github.com/bermi/password-generator

That will generate you a password with a customizable length that even can be memorable.

There's also several example on the link provided.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top