mercredi 27 mai 2020

JavaScript - Password Generator (checkbox)

I am working for an assignment about a password generator. Here is my HTML and JavaScript. When I click the checkbox for number and symbol, the result returns a password including "undefined". I guess the issue is from my if-else statement for checkbox status. What the result I expected is that whichever I click , the result does not include any letter of "undefined". Could someone help me with this issue? Thank you!

const btn = document.querySelector(".btn")
function getChar(num, char) {
  if (document.querySelector("input[name=" + num + "]").checked) {
    return char
  }
}
btn.addEventListener("click", e => {


  if (!document.querySelector("input[name=en]").checked && !document.querySelector("input[name=num]").checked && !document.querySelector("input[name=sym]").checked) {
    return
  }

  let password = ""
  let alphabet = "abcdefghijklmnopqrstuvwxyz"
  let number = "0123456789"
  let symbol = "!@#$%^&*+="

  password += getChar("en", alphabet)
  password += getChar("num", number)
  password += getChar("sym", symbol)


  let result = ""
  for (let i = 0; i < 10; i++) {
    let num = Math.floor(Math.random() * password.length)
    result += password[num]
  }
  console.log(result)
  document.querySelector(".result").innerHTML = result
})
<div class="container">
    <div class="english">
      <label for="en">English letter</label>
      <input type="checkbox" name="en">
    </div>
    <div class="number">
      <label for="num">Number</label>
      <input type="checkbox" name="num">
    </div>
    <div class="symbol">
      <label for="sym">Symbol</label>
      <input type="checkbox" name="sym">
    </div>
    <button class="btn">Generate</button>
    <div class="result"></div>
 </div>

Aucun commentaire:

Enregistrer un commentaire