Home > database >  Why is my password generator showing the password before I click the button?
Why is my password generator showing the password before I click the button?

Time:12-13

The function generates, but it does it every time I refresh the browser, I'm trying to make it so every time I click the button, the string appears and then generates a new one. Any help would be appreciated!!

    <body>
  <button type="button" onclick="generatePassword()">GENERATE</button>
  <p id="demo"></p>

<script>

function generatePassword(length = 12) {
    let generatedPassword = "";

    const validChars = "0123456789"  
        "abcdefghijklmnopqrstuvwxyz"  
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"  
        ",.-{} !\"#$%/()=?";

    for (let i = 0; i < length; i  ) {
        let randomNumber = crypto.getRandomValues(new Uint32Array(1))[0];
        randomNumber = randomNumber / 0x100000000;
        randomNumber = Math.floor(randomNumber * validChars.length);

        generatedPassword  = validChars[randomNumber];
    }

    return generatedPassword;

  }

  document.getElementById("demo").innerHTML = generatePassword();


</script>

</body>

CodePudding user response:

Because you're calling generatePassword in the code itself. Use this instead

    <body>
  <button type="button" onclick="generatePassword()">GENERATE</button>
  <p id="demo"></p>

<script>

function generatePassword(length = 12) {
    let generatedPassword = "";

    const validChars = "0123456789"  
        "abcdefghijklmnopqrstuvwxyz"  
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"  
        ",.-{} !\"#$%/()=?";

    for (let i = 0; i < length; i  ) {
        let randomNumber = crypto.getRandomValues(new Uint32Array(1))[0];
        randomNumber = randomNumber / 0x100000000;
        randomNumber = Math.floor(randomNumber * validChars.length);

        generatedPassword  = validChars[randomNumber];
    }

    document.getElementById("demo").innerHTML = generatedPassword;
  }
</script>

</body>

Or even better, don't say onclick="..." on the element itself:

    <body>
  <button type="button" id="generateButton">GENERATE</button>
  <p id="demo"></p>

<script>

function generatePassword(length = 12) {
    let generatedPassword = "";

    const validChars = "0123456789"  
        "abcdefghijklmnopqrstuvwxyz"  
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"  
        ",.-{} !\"#$%/()=?";

    for (let i = 0; i < length; i  ) {
        let randomNumber = crypto.getRandomValues(new Uint32Array(1))[0];
        randomNumber = randomNumber / 0x100000000;
        randomNumber = Math.floor(randomNumber * validChars.length);

        generatedPassword  = validChars[randomNumber];
    }

    return generatedPassword;
  }

  document.getElementById("generateButton").addEventListener("click", () => document.getElementById("demo").textContent = generatePassword());

</script>

</body>
  • Related