Reputation: 480
I'm a programming newbie trying to make a function that asks for a password, but will display an error message if the password attempt is wrong more than five times. I have tried fiddling around with those code a bunch of different ways and it just won't work. I have a variable called count that starts as 0, and each time a wrong password is entered, 1 is supposed to be added to count, and once count is greater than 5, the error message is supposed to be displayed.
document.getElementById("word-checker").onclick = function () {
var count = 0;
var inputValue = document.getElementById("text-input").value;
var secretWord = "password123";
if (count > 5) {
alert("You have had 5 unsuccessful login attempts. You account has been temporarily locked.");
} else if (inputValue == secretWord) {
alert("Your answer is correct!");
document.getElementById("text-input").value = "";
} else if (inputValue!==secretWord) {
count++;
alert("Your answer is incorrect. Please try again.");
document.getElementById("text-input").value = "";
}
}
This is driving me insane. I'm sure it's a simple beginner's mistake though. Any input that would help me understand why this won't work would be met with a lot of gratitude.
Upvotes: 0
Views: 75
Reputation: 6565
You are resetting count
to 0
every time the click event is triggered:
document.getElementById("word-checker").onclick = function () {
var count = 0; // <-- button clicked, set the value to zero.
// ...
}
This means that count
will never get to 5
(in fact, it never gets to be > 1
either, as when count++
increments the value to 1
, it is set back to 0
on the next click). Consequently, the if (count > 5)
part of the if statement will never be triggered.
You need to declare count
outside of the click event:
var count = 0;
document.getElementById("word-checker").onclick = function () {
// use count here
// ...
}
Upvotes: 6
Reputation: 1570
you are redefining count as 0 every time on the click event. You need to define count as a global outside the function and then ++ on every error. Also, try to correct your indentation as it helps reading.
Upvotes: 1