skip to Main Content

I am making a program where you have to guess the secret password. If you don’t then the program will alert you. I expect that the problem lies with label. I have tried innerText, innerHTML, TextContent and it still doesn’t work and doesn’t report any issues. Here is the code:

let button = document.getElementById("button")
let input = document.getElementById("input")
let label = document.getElementById("label")
let guess = false;
let password = "Monkey4";

function myFunction() {
  while (guess) {
    if (password = "Monkey4") {
      guess = true;
      label.textContent = "gg";
    } else {
      alert("try again");
    }
  }
}
<input id="input">
<button id="button" onclick="myFunction()">Check</button>
<label id="label">Guess it and the text will change</label>

2

Answers


  1. Your while loop will only run when guess is true, which you have set to false directly before initializing myFunction(). By design, the loop will never run in this state, and you’re not seeing any errors because there aren’t any. You’ll need to modify the logic of the while loop check to something like the following:

    while (guess === false) {
        // Some logic
    }
    
    Login or Signup to reply.
  2. You don’t need a while loop at all. When the user clicks the button, it should just check the password they entered in the input field once. If you use a loop, it won’t allow them to change the password.

    As mentioned in the comments, you have to use == or === to compare things.

    let button = document.getElementById("button")
    let input = document.getElementById("input")
    let label = document.getElementById("label")
    let correctPassword = "Monkey4";
    
    function myFunction() {
      let password = input.value;
      if (password == correctPassword) {
        label.textContent = "gg";
      } else {
        alert("try again");
      }
    }
    <input id="input">
    <button id="button" onclick="myFunction()">Check</button>
    <label id="label">Guess it and the text will change</label>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search