Random password generator using

I fixed your code and made some observations in the snippet

// Assignment Code

var charString = ["ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklnmopqrstuvwxyz", "0123456789", "[email protected]#$%^&*()-_=+"];

var userInput = [];

var password = "";

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

// Write password to the #password input
function writePassword() {
    password = generatePassword();
    var passwordText = document.querySelector("#password");

    passwordText.value = password;
}

// Character length prompt
function generatePassword() {
    var characterLength = 0
    while ((characterLength < 8 || characterLength > 128) || Number.isInteger(characterLength) === false) {
        characterLength = parseInt(prompt("How many characters would you like your password to be? (8-128)"));
    }

    var upper = false
    var lower = false
    var number = false
    var symbol = false

    while (!upper && !lower && !number && !symbol) {

        // Uppercase pop up
        upper = confirm("Click OK to confirm uppercase characters");

        // Lowercase pop up
        lower = confirm("Click OK to confirm lowercase characters");

        // Numeric pop up
        number = confirm("Click OK to confirm numeric characters");

        // Special charcter  pop up
        symbol = confirm("Click OK to confirm special characters ([email protected]#$%^&*()-_=+)");
    }

    // userInput is an array, so you should push values into it.
    if (upper) {
        userInput.push(charString[0]);
    }

    if (lower) {
        userInput.push(charString[1])
    }

    if (number) {
        userInput.push(charString[2])
    }

    if (symbol) {
        userInput.push(charString[3])
    }

    var password = "";

    // join all array elements into a single one, and then split in order
    // to get an array of characters
    userInput = userInput.join("").split("");

    // You should start your for statement at position 0, not 1
    // and I guess it should be < than characterLength, not userInput.length
    for (var i = 0; i < characterLength; i++) {
        // Math.random is a function so you were missing the parenthesis Math.random()
        // also Math.random() should be times userInput.length
        // so they should be inside the same parenthesis
        var index = (Math.floor(Math.random() * userInput.length));
        password = password + userInput[index]
    }

    return password
}

// Add event listener to generate button
generateBtn.addEventListener("click", writePassword);
<button id="generate">Generate</button>
<br>
<input type="text" id="password">

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top