RomanK
RomanK

Reputation: 154

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>

Upvotes: 3

Views: 11005

Answers (2)

pparas
pparas

Reputation: 549

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

Upvotes: 0

Mike Cluck
Mike Cluck

Reputation: 32511

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>

Upvotes: 1

Related Questions