-1

Some pretty simple code, although i cant figure out why its not working properly. When run, it asks for password but does nothing once password has been entered. It is supposed to give the user 3 attempts to enter password correctly, displaying correct/incorrect password where appropriate. Could anyone help point out what ive done wrong here, thanks :)

Here is my code:

<html>
<head>
<title>Password Entry</title>
<script>

function passwordEntry(vP)
{
i=0
password = prompt("Please enter password")
i++
if(password != vP){
    do{
        i++
        password = prompt("Password incorrect" <br> "Please re-enter password")
    }while (password != vP && i<=3)
}
    if(password == vP){
        alert("Password correct")
    }
}

var validPassword = "123XY"
passwordEntry(validPassword)

</script>
</head>
</html>
Ivar
  • 6,138
  • 12
  • 49
  • 61
  • Does this answer your question? [New line in JavaScript alert box](https://stackoverflow.com/questions/1841452/new-line-in-javascript-alert-box) – Ivar Dec 17 '19 at 21:40
  • 1
    Replace `"Password incorrect"
    "Please re-enter password"` with `"Password incorrect\nPlease re-enter password"`.
    – Ivar Dec 17 '19 at 21:40
  • 1
    Does this answer your question? [Can I add a
    and links to a javascript alert?](https://stackoverflow.com/questions/591130/can-i-add-a-br-and-links-to-a-javascript-alert)
    – AndrewL64 Dec 17 '19 at 21:41

1 Answers1

0

Within strings, you use \n to add line breaks. Updated code below:

function passwordEntry(vP) {
  i = 0;
  password = prompt("Please enter password");
  i++;
  if (password != vP) {
    do {
      i++;
      password = prompt("Password incorrect \nPlease re-enter password");
    } while (password != vP && i <= 3);
  }
  if (password == vP) {
    alert("Password correct");
  }
}
var validPassword = "123XY";
passwordEntry(validPassword);

but it can use quite a bit of optimization. Prompting for a password on the client side is a wholly bad idea since users can access it.

Updated code using if statements:

function passwordEntry(vP) {
  for (i = 0; i <= 3; i++) {
    if (i == 0) { // initial attempt
      password = prompt("Please enter password");
    } else if (i > 3) {
      alert("Denied");
    } else if (password != vP) {
      password = prompt("Password incorrect \nPlease re-enter password");
    } else if (password == vP) {
      alert("Password correct");
      i = 4; // stop prompting
    }
  }
}
var validPassword = "123XY";
passwordEntry(validPassword);
franklylately
  • 1,112
  • 10
  • 12