Assuming your password box has the CSS id ‘password’ you can clear it with this javascript:
document.querySelector("#password").value = ""
Assuming your password box has the CSS id ‘password’ you can clear it with this javascript:
document.querySelector("#password").value = ""
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 class="wrapper">
<header>
<h1>Password Generator</h1>
</header>
<div class="card">
<div class="card-header">
<h2>Generate a Password</h2>
</div>
<div class="card-body">
<textarea readonly id="password" placeholder="Your Secure Password" aria-label="Generated Password"></textarea>
</div>
<div class="dojo">
</div>
<div class="card-footer">
<button id="generate" class="btn">Generate Password</button>
</div>
</div>
</div>
You have made a function, called writePassword()
. But the you put the declaration of both and generatedPassword
outside 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 = '';
...
}
Right before the for
loop, clear this variable:
generatedPassword = "";
Stop using prompt()
it is horrible UX. The user has to enter a minimum of 1 and a maximum of 5 interactions, but using prompt()
forces user to interact 5 times minimum. Use a <form>
and events if you need user interaction.
Almost forgot the question.
“How Can I reset the Text value to an empty string after I’ve randomly generated a password with javascript?”
In the example you click the Clear button.
Or programmatically:
document.querySelector(selectorOfElement).value = '';
In the example it’s very easy after referencing the <form>
:
const form = document.forms.ID_or_Name.elements;
form.ID_or_Name.value ='';
If your concern is that each time a password is generated it just adds on to the previous one, you need to add one of those lines previously mentioned in a event handler like a click to a different button or add the line to the beginning of your event handler. Of course if you try to learn from my example such things wouldn’t be an issue.
Details are commented in example below
// Put all arrays in a single array
const characters = [
['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'],
["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"],
["0", "1", "3", "4", "5", "6", "7", "8", "9"],
["+", "-", "&", "|", "!", "(", ")", "{", "}", "[", "]", "^", "~", "*", "?", ":"]
];
// Array shuffling function
function shuffle(array) {
let qty = array.length,
temp, i;
while (qty) {
i = Math.floor(Math.random() * qty--);
temp = array[qty];
array[qty] = array[i];
array[i] = temp;
}
return array;
};
// Invoked on "submit" event
function manageUI(e) {
// Prevent form <from> sending data to server
e.preventDefault();
/*
References all <input>, <button>, <fieldset>, <textarea> in <form>
*/
const IO = this.elements;
// Collect checkboxes into an array
const checks = [...IO.char];
/*
Get the string from IO.qty and covert it into a real +number
*/
const size = +IO.qty.value;
/*
This will go through the 2D array and skip any sub-array that corresponds
with an unchecked checkbox. It return a single array with the remaining
sub-arrays merged.
*/
const chars = checks.flatMap(char => char.checked ? characters[+char.value] : []);
// The array is then shuffled
const shuffled = shuffle(chars);
/*
A new array is made at the length of IO.qty.value.
It will fill itself up with the chars in the shuffled array.
*/
const password = [...Array(size)].map((_, i) => shuffled[i]);
/*
The password array is converted to a string.
IO.pass and IO.text get the password as their .value
Finally, IO.final is revealed
*/
IO.pass.value = password.join('');
IO.text.value = IO.pass.value;
IO.final.classList.remove('hide');
};
/*
Invoked when a "click" event happens on IO.text or IO.pass
*/
function showPass(e) {
const IO = this.elements;
// This is the tag user actually clicked
const clicked = e.target;
/*
If clicked is IO.pass OR IO.text...
...toggle the .gone' class on both of them (only one can be visible).
Also, there's .adjust class used to center the icon vertically.
*/
if (clicked.name == 'pass' || clicked.name == 'text') {
IO.pass.classList.toggle('gone');
IO.text.classList.toggle('gone');
if (clicked.name == 'pass') {
clicked.parentElement.classList.add('adjust');
} else {
clicked.parentElement.classList.remove('adjust');
}
}
};
/*
Invoked when a "reset" event happens <form> will reset and IO.final
disappears
*/
function clearForm(e) {
const IO = this.elements;
IO.final.classList.add('hide');
};
// Reference <form>
const UI = document.forms.UI;
/*
These are on event properties they are like .addEventListener() except
they only listen on the bubbling phase. The method .aEL() can listen on
bubbling phase or capture phase. I prefer onevent props because they are
terse and rarely need to listen on capture phase.
*/
UI.onsubmit = manageUI;
UI.onclick = showPass;
UI.onreset = clearForm;
html {
font: 2ch/1.15 Consolas
}
header {
margin-bottom: -16px;
}
main>fieldset legend {
margin-bottom: -12px
}
label {
display: block;
width: 100%;
}
input,
textarea,
button {
display: inline-block;
vertical-align: middle;
font: inherit;
}
button {
float: right;
cursor: pointer;
}
[name='char'] {
width: 2ch;
height: 2ch;
}
[name='qty'] {
text-align: center;
}
[name='final'] label {
margin: -12px 8px 4px 0;
}
[name='final'] label::after {
content: ' 1f511';
font-size: 1.25rem;
vertical-align: bottom;
cursor: pointer;
}
[name='final'] label.adjust::after {
vertical-align: middle;
}
[name='pass'],
[name='text'] {
min-width: 21ch;
height: 20px;
}
[name='text'] {
resize: vertical;
}
.hide {
visibility: hidden;
}
.gone {
display: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Password Generator</title>
</head>
<body>
<form id='UI'>
<header>
<h1>Password Generator</h1>
</header>
<main>
<fieldset>
<legend>
<h2>Generate a Password</h2>
</legend>
<label>Number of Characters: <input name='qty' type='number' min='8' max='40' value='' required></label>
<label>Uppercase Letters: <input name='char' type='checkbox' value='0' checked></label>
<label>Lowercase Letters: <input name='char' type='checkbox' value='1' checked></label>
<label>Numbers: <input name='char' type='checkbox' value='2' checked></label>
<label>Special Characters:
<input name='char' type='checkbox' value='3' checked></label>
</fieldset>
<menu>
<button type='reset'>Clear</button>
<button>Generate Password</button>
</menu>
</main>
<footer>
<fieldset name='final' class='hide'>
<legend>
<h3>Password Completed</h3>
</legend>
<label><input name='pass' type='password' readonly>
<textarea name='text' class='gone' rows='2' cols='21' readonly></textarea></label>
</fieldset>
</footer>
</form>
</body>
</html>
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 class="wrapper">
<header>
<h1>Password Generator</h1>
</header>
<div class="card">
<div class="card-header">
<h2>Generate a Password</h2>
</div>
<div class="card-body">
<textarea readonly id="password" placeholder="Your Secure Password" aria-label="Generated Password"></textarea>
</div>
<div class="dojo">
</div>
<div class="card-footer">
<button id="generate" class="btn">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
Have
hello I tried this , I put……… let passwordText = document.querySelector(“#password”);…… passwordText.value= ”;……. at the beginning of the script but it still keeps merging the last password with the new password instead of resetting it to an empty string as I designated