How to check with loops how many times user punche

2020-01-20 02:40发布

问题:

On my homework assignment I have to set up a test that ask the user for the password ( three times). If the user punches wrong password three times, then I must display a message " Wrong password". Also I have to take into account three variants of the username and password

I am thinking that I set up a predefined passwords like "test", "password" and so on. The same I will do with the usernames. So basically I just know how to count how many times the user punches the username and password...

<!DOCTYPE html>
<html>

  <body>

  <script>

  var password = "";

  while(password = "" || password != "password"||username !="Bella"||username="") {
username=prompt ("What´s your username?);    
passord = prompt("What´s the password?");
  }

  alert("That was correct!");

  </script>

  </body>
</html>

What´s the username? What´s the password?

wrong - typed 3 times That was correct

回答1:

<!DOCTYPE html>
<html>

  <body>

  <script>
    var incorrectCount = 0;
    var correctPassword = "randompassword"
    function checkPassword(){
        var enteredPassword  = document.getElementById("txtpassword").value;
        if(enteredPassword != correctPassword)
            incorrectCount++
        else{
            incorrectCount = 0
            document.getElementById("userMessage").innerHTML = "Correct Password !!"
        }

        if(incorrectCount == 3){
            document.getElementById("userMessage").innerHTML = "Incorrect password entered 3 or more times"
            document.getElementById("userMessage").style.visibility = "visible";
        }
    }
  </script>

  <input type="text" id="txtpassword" name ="txtpassword">
  <input type="button" id="loginbutton" value="Login" onclick="checkPassword()"><br>
  <label id="userMessage" style="visibility:hidden;"></label>
  </body>
</html>
  1. You do not need a loop for this.
  2. You can just have a global variable and increment it every time user enters wrong password.
  3. Once the counter reaches 3, you can show the message.
  4. Please refer the code above.

Also, try searching for stuff like - how can I validate a input, how can I display/show a message - this will help you in learning