Home > Blockchain >  How Can I reset the Text value to an empty string after I've randomly generated a password with
How Can I reset the Text value to an empty string after I've randomly generated a password with

Time:03-27

var generateBtn = document.querySelector("#generate");

// put our characters into seperate arrays
const uppercaseLetters = ['A', 'B', 'C', 'D', "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "X", "Y", 'Z']

const lowercaseLetters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

const numeric = ["0", "1", "3", "4", "5", "6", "7", "8", "9"]

const specialCharacters = [" ", "-", "&&", "||", "!", "(", ")", "{", "}", "[", "]", "^",
  "~", "*", "?", ":",
]

//create an empty password array and empty generatedPassword string
let passwordArry = [];

let generatedPassword = '';

//create variables for included types


//write a function to generate the password
function writePassword() {

  //prompt to the user how many characters they want
  let passwordLength = window.prompt(`How many characters? enter between 8 & 128`);

  //if user doesnt enter a password or the input is nan
  while (!passwordLength || isNaN(passwordLength)) {
    window.alert(`this field cannot be empty & has to be an integer`);
    passwordLength = window.prompt(`How many characters? enter between 8 & 128`);
  }

  //if password length is les than 8 or more than 128, reprompt
  if (passwordLength < 8 || passwordLength > 128) {
    window.alert(`Password must be between 8 & 128 characters`);
    passwordLength = window.prompt(`How many characters? enter between 8 & 128`);
  }

  let includeUppercase;
  let includeLowercase;
  let includeNumeric;
  let includeSpecialCharacter

  //alert the user to input on every prompt

  while (!includeNumeric && !includeSpecialCharacter && !includeLowercase && !includeUppercase) {
    alert("check all")
    includeNumeric = prompt("Should include numeric character, enter yes or no").toLowerCase()
    includeSpecialCharacter = prompt("Should include special character,enter yes or no").toLowerCase()
    includeLowercase = prompt("Should include lowercase character,enter yes or no").toLowerCase()
    includeUppercase = prompt("Should include uppercase character,enter yes or no").toLowerCase()
  }

  //if user selects to include any of these characters by entering yes then we will put those characters into an array, if the users enter anything else then the program will do nothing and go to the next prompt

  if (includeNumeric === "yes") {
    passwordArry = passwordArry.concat(numeric)

  }
  if (includeLowercase === "yes") {
    passwordArry = passwordArry.concat(lowercaseLetters)

  }
  if (includeUppercase === "yes") {
    passwordArry = passwordArry.concat(uppercaseLetters)

  }
  if (includeSpecialCharacter === "yes") {
    passwordArry = passwordArry.concat(specialCharacters)

  }

  // now that we have added the types to the password array, we now loop through the array to grab random characters
  // generates a random password from the entered password length
  for (let i = 0; i < passwordLength; i  ) {
    //create a variable to hold the random number , we multiply the random number by the length of the whole password array
    const randomLength = Math.floor(Math.random() * passwordArry.length)
    //the random length is a number and we use that number for the index of the password array
    generatedPassword = generatedPassword   passwordArry[randomLength];

    let passwordText = document.querySelector("#password");

    passwordText.value = generatedPassword;

  }


}

generateBtn.addEventListener('click', writePassword);
<div >
  <header>
    <h1>Password Generator</h1>
  </header>
  <div >
    <div >
      <h2>Generate a Password</h2>
    </div>
    <div >
      <textarea readonly id="password" placeholder="Your Secure Password" aria-label="Generated Password"></textarea>
    </div>
    <div >

    </div>
    <div >
      <button id="generate" >Generate Password</button>
    </div>
  </div>
</div>

I tried to set passwordText.value to and empty string at he beginning of the write password function but that would not work because passwordText.value is not defined until the end of the function. I also tried to create a function called PlayAgain to run the writePassword function again if the user chooses to and set the text value to an empty string but that didnt work either

CodePudding user response:

document.querySelector("#password").value = ""

CodePudding user response:

Fixed Code:

var generateBtn = document.querySelector("#generate");

// put our characters into seperate arrays
const uppercaseLetters = ['A', 'B', 'C', 'D', "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "X", "Y", 'Z']

const lowercaseLetters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

const numeric = ["0", "1", "3", "4", "5", "6", "7", "8", "9"]

const specialCharacters = [" ", "-", "&&", "||", "!", "(", ")", "{", "}", "[", "]", "^",
  "~", "*", "?", ":",
]




//create variables for included types


//write a function to generate the password
function writePassword() {
  //create an empty password array and empty generatedPassword string
  let passwordArry = []; 
  let generatedPassword = '';
  //prompt to the user how many characters they want
  let passwordLength = window.prompt(`How many characters? enter between 8 & 128`);

  //if user doesnt enter a password or the input is nan
  while (!passwordLength || isNaN(passwordLength)) {
    window.alert(`this field cannot be empty & has to be an integer`);
    passwordLength = window.prompt(`How many characters? enter between 8 & 128`);
  }

  //if password length is les than 8 or more than 128, reprompt
  if (passwordLength < 8 || passwordLength > 128) {
    window.alert(`Password must be between 8 & 128 characters`);
    passwordLength = window.prompt(`How many characters? enter between 8 & 128`);
  }

  let includeUppercase;
  let includeLowercase;
  let includeNumeric;
  let includeSpecialCharacter;

  //alert the user to input on every prompt

  while (!includeNumeric && !includeSpecialCharacter && !includeLowercase && !includeUppercase) {
    alert("check all");
    includeNumeric = prompt("Should include numeric character, enter yes or no").toLowerCase();
    includeSpecialCharacter = prompt("Should include special character,enter yes or no").toLowerCase();
    includeLowercase = prompt("Should include lowercase character,enter yes or no").toLowerCase();
    includeUppercase = prompt("Should include uppercase character,enter yes or no").toLowerCase();
  }

  //if user selects to include any of these characters by entering yes then we will put those characters into an array, if the users enter anything else then the program will do nothing and go to the next prompt

  if (includeNumeric === "yes") {
    passwordArry = passwordArry.concat(numeric);

  }
  if (includeLowercase === "yes") {
    passwordArry = passwordArry.concat(lowercaseLetters);

  }
  if (includeUppercase === "yes") {
    passwordArry = passwordArry.concat(uppercaseLetters);

  }
  if (includeSpecialCharacter === "yes") {
    passwordArry = passwordArry.concat(specialCharacters);

  }

  // now that we have added the types to the password array, we now loop through the array to grab random characters
  // generates a random password from the entered password length
  for (let i = 0; i < passwordLength; i  ) {
    //create a variable to hold the random number , we multiply the random number by the length of the whole password array
    const randomLength = Math.floor(Math.random() * passwordArry.length)
    //the random length is a number and we use that number for the index of the password array
    generatedPassword = generatedPassword   passwordArry[randomLength];

    let passwordText = document.querySelector("#password");

    passwordText.value = generatedPassword;

  }


}

generateBtn.addEventListener('click', writePassword);
<div >
  <header>
    <h1>Password Generator</h1>
  </header>
  <div >
    <div >
      <h2>Generate a Password</h2>
    </div>
    <div >
      <textarea readonly id="password" placeholder="Your Secure Password" aria-label="Generated Password"></textarea>
    </div>
    <div >

    </div>
    <div >
      <button id="generate" >Generate Password</button>
    </div>
  </div>
</div>

You have made a function, called writePassword(). But the you put the declaration of both and generatedPasswordoutside of the function. So it won't reset every time you run it. Here's why:

First, the generatedPassword you declared outside of the writePassword() function

let generatedPassword = "";

will only reset(clear the variable) when the page loads. It does not reset anymore. Since you set the function to run when the button is clicked, let's put the variable assignment inside the function. If not, it will keep concatenating(joining) from the passwordArry array.

There is also another problem. Here is an example: So, in the first time you generate special characters and lowercase letters. But in the second time you only want numbers and uppercase letters, but it still says special characters and lowercase letters including what you want this time.

This is because the array assignment is also outside of the writePassword() function. When you put special characters, it will put the special characters array into the passwordArry[] and generate a password based on random elements in the password array. But do it a second time, and this time you want numbers, but it only adds on to the array. So instead you get extra special characters when you don't want to. So, if you put the passwordArry into the function, it will work.

...
function writeFunction(){
    let passwordArry = [];

    let generatedPassword = '';
    ...
}

CodePudding user response:

Right before the for loop, clear this variable:

generatedPassword = "";
  • Related