Home > Net >  i am trying to create a simple login page using javascript that will allow the user to input their u
i am trying to create a simple login page using javascript that will allow the user to input their u

Time:12-06

i am new to javascript and i was not able to figure out how to do it correctly. i was trying to create a simple page that will allow the user to input their username and password correctly but if they enter an invalid username or password 3 times, they won't be allowed to input again. here is my code:

var UserInfo=[
{
    username:"elliot",
    password:"123"
},
{
    username:"nicholas",
    password:"456"
},
{
    username:"rose",
    password:"789"
},
{
    username:"samantha",
    password:"987"
},
{
    username:"austin",
    password:"654"
}
]

document.getElementById("btn").onclick=function(){
var username=document.getElementById("un").value
var password=document.getElementById("pw").value

    for(i=0;i<4;i  ){
        if (username==UserInfo[i].username && password==UserInfo[i].password){
            alert("Successfully logged in!");
        }else{
            alert("Please try again.");
        }
    }
}

CodePudding user response:

You cannot use for loop for that. You need a counter to count how many attempts and increase that counter every time the user makes a mistake. Try something like this:

let attempts = 0
document.getElementById("btn").onclick=function(){
var username=document.getElementById("un").value
var password=document.getElementById("pw").value

    if(attempts>=3){
        alert("Sorry. Too many attempts.");
    }
    else{
        if (UserInfo.find(el=> el.username === username && el.password === password)){
            alert("Successfully logged in!");
        }else{
            attempts  
            alert("Please try again.");
        }
    }
    
}
  • Related