At least, I think that the iterations are stopping after the first loop. I'm trying to get my password to loop 3 times when the incorrect password is inputted before sending an error message. When I enter one incorrect password and click my submit button, the iterations stop. New to coding, so please let me know if I'm doing something wrong.
My JS (button on-click
function):
var password = "password";
var notif = document.getElementById("notif");
var entryCount = 0;
var entryLimit = 3;
var error = false;
function inputPW(){
for(i = 0; i < 3; i ){
notif.innerHTML = "";
if(passwordInp.value === password){
notif.innerHTML = "You got it!";
break;
}
else if(i < 3){
notif.innerHTML = "Incorrect password. Please try again.";
}
else{
notif.innerHTML = "Password limits exceeded.";
}
}
}
My HTML (body only):
<h1>Password Getter</h1>
<p>Password:</p>
<input id = "passwordInp" type="text" placeholder="Password" autofocus>
<button id="enterBtn" type="button" onclick="inputPW()">Submit</button>
<p id="notif"></p>
<script src="JSscript.js"></script>
CodePudding user response:
//these constants won't change during execution
const LIMIT = 3;
const PASSWORD = 'password';
let entryCount = 0; // a global variable
let authorized = true; //can we still try?
function handleInput(inp){
if(!authorized){
return; //we do nothing if we're not authorized anymore
}
const matches = inp == PASSWORD;
if(matches){
//do 'success' thing
} else if(entryCount < LIMIT){
entryCount ;
//do 'not success' thing
} else{
authorized = false;
//do 'unauthorized' thing
}
}
<h1>Password Getter</h1>
<p>Password:</p>
<input id = "passwordInp" type="text" placeholder="Password" autofocus>
<button id="enterBtn" type="button" onclick="handleClick(passwordInp.value)">Submit</button>
<p id="notif"></p>
<script src="JSscript.js"></script>
CodePudding user response:
for loop runs the same code in a single go and not wait for user's input. since the input didnt change while it was running it runs only once. instead call the function when the user clicks the submit button and increment a global variable.
var password = "password";
var notif = document.getElementById("notif");
var passwordInp = document.getElementById("passwordInp");
var entryCount = 0;
var entryLimit = 3;
var error = false;
var i = 0;
function inputPW(){
notif.innerHTML = "";
if(passwordInp.value === password){
notif.innerHTML = "You got it!";
break;
else if(i < 3){
notif.innerHTML = "Incorrect password. Please try again.";
}
else{
notif.innerHTML = "Password limits exceeded.";
}
}
}