简体   繁体   中英

onClick Button Only Works Once

I have a button that checks input text to see if it is the right password. The problem is that the button only works once and when you click multiple times it doesn't run the function over and over again.

My Code:

<html>

<head>
  <title>Password</title>
  <script>
  function passcheck() {
    var attempts = 5;
    var q = document.getElementById('txt').value;
    if (q == "12345") {
      document.getElementById("result").innerHTML = "You're In!";
    } else {
      attempts--;
      document.getElementById("result").innerHTML = "Wrong password, You Have " + attempts + " Tries Left!";
    }
  }
  </script>
</head>

<body>
  <font face="Verdana" size="5"><b>Enter Your Password:</b></font>
  <br/><br/>
  <input id="txt" type="text" onclick="this.select()" style="text-align:center;" width="25">
  <button type="button" onclick="passcheck()">Submit!</button>
  <p id="result"></p>

</body>

</html>

It is being called multiple times, but you aren't seeing a change because attempts is defined inside of the function. That means that every time you run that functions, attempts is being reset to 5 . To fix that, move the attempts declaration outside of the function.

 var attempts = 5; // Moved to here so we don't reset the value function passcheck() { var q = document.getElementById('txt').value; if (q == "12345") { document.getElementById("result").innerHTML = "You're In!"; } else { attempts--; document.getElementById("result").innerHTML = "Wrong password, You Have " + attempts + " Tries Left!"; } } 
 <font face="Verdana" size="5"><b>Enter Your Password:</b></font> <br/> <br/> <input id="txt" type="text" onclick="this.select()" style="text-align:center;" width="25"> <button type="button" onclick="passcheck()">Submit!</button> <p id="result"></p> 

You are initializing the value of "attempts" and decrementing it every time you call the function. Hence it seems like the function is being called only once.

Move the deceleration of the variable outside the function. Something like

var attempts = 5;
function passcheck() {
  //code here ...
}

Another slightly better way would be to make use of localStorage or sessionStorage or even using cookies.

Thanks, Paras

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM