Search code examples
javascripthtmlfor-looppasswords

Simple JavaScript password checker won't loop after the first iteration


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>

Solution

  • //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>