Last updated on December 27th, 2022 at 11:04 am

This code will create passwords randomly using simple Javascript. It also contains an option to provide the length of the password.

By default I have given length of the password as 8 but it is up to your use case on what that value should be.

Change it inside onclick="password(8)" 

We can also pass a value to the function as password(8,true) or password(8,false). If value is true then you can get special characters in your password.

<script type="text/javascript">
//script from Mistonline.in (Please dont remove this line)
function password(length, special) {
  var iteration = 0;
  var password = "";
  var randomNumber;
  if(special == undefined){
      var special = false;
  }
  while(iteration < length){
    randomNumber = (Math.floor((Math.random() * 100)) % 94) + 33;
    if(!special){
      if ((randomNumber >=33) && (randomNumber <=47)) { continue; }
      if ((randomNumber >=58) && (randomNumber <=64)) { continue; }
      if ((randomNumber >=91) && (randomNumber <=96)) { continue; }
      if ((randomNumber >=123) && (randomNumber <=126)) { continue; }
    }
    iteration++;
    password += String.fromCharCode(randomNumber);
  }
  document.getElementById('pwd').innerHTML=password;
}
</script>


The above Javascript will simple display some random characters according to the length and we update the div element with ID = PWD

We are calling the Javascript function by triggering a button.

The New Password is <font color="red"><div id="pwd"></div></font>
<form>
  <input onclick="password(8)" type='button' value="Generate Random Password Now" id="submit"/>
  <input onclick="password(8,true)" type='button' value="Generate Random Password With Special Char" id="submit"/>
</form>


DEMO

Leave a Reply

Your email address will not be published. Required fields are marked *