Thulaz Thulaz - 17 days ago 5
Javascript Question

Attempt to display prompt until correct entry is entered in using Javascript

I'm trying to make "Enter your Password: " prompt appear until the correct password is entered. There is no limit to the attempts of password entry. So far I came up with this code using Javascript

function promptPassword( )
{

var name = prompt ("Enter your Username: ");
var pwd = prompt ("Enter your Password: ");

if (pwd == 'P@ssw0rd'){
alert("Password is correct, you are allowed to enter the site");
}

while (pwd != 'P@ssw0rd'){
alert("Login is incorrect");
prompt ("Enter your Password: ");
}

}


When I enter the correct password in first attempt the correct alert displays and it goes away when I click 'ok', which is expected.
When I type wrong passwords it keeps prompting to enter the password again, which is also as expected.
But the problem here is when I first enter wrong password and then enter right password in the next attempts, it still keeps prompting to enter the password again. Once the correct password is entered, "Password is correct, you are allowed to enter the site" alert should display and should go away, when 'ok' is clicked

Answer

Your prompt return value isn't being assigned in the while loop. Try this:

function promptPassword( )
{

var name = prompt ("Enter your Username: ");
var pwd = prompt ("Enter your Password: ");

while (pwd != 'P@ssw0rd'){
alert("Login is incorrect");
prompt ("Enter your Password: ");
}

alert("Password is correct, you are allowed to enter the site");

}