Search code examples
javascriptformsauthenticationpasswordsverification

Javascript Password Verification window.location.replace


I have a site that I want to make a JavaScript login form.

Not like a perfect username & password login, But I want to build a password verification login. I want the user to redirect to private.html when they get it right, and to error.html when they get it wrong.

This is the HTML:

<script type="text/javascript">
function checkForm() {
  x = document.getElementById("holy").value
  if (x == "mangos") {
    alert("Right Password!");
    window.location.replace("private.html");
  }
  else {
    alert("Wrong Password!");
    window.location.replace("home.html");
  }
}
</script>
<center>
<form class="form-container">
<center>
<div class="form-title"><h2>Login</h2></div>
<div class="form-title">Username</div>
<input class="form-field" type="text" name="username" /><br />
<div class="form-title">Password</div>
<input class="form-field" type="password" id="holy" name="password" /><br />
<div class="submit-container">
<button onclick="checkForm()" class="submit-button">Login</button>
</div> 
</center>
</form>

Apparently, the alert section in the function works, but then the next part of code, which is the window.location.replace doesn't work at all. Instead, the URL becomes

.com/password.html?username=asd&password=mangos

How should I do/fix this?


Solution

  • This happens because the form is getting submitted, which is it's default behavior. To circumvent this, write a return false at the end of your checkForm() function.

    function checkForm() {
      x = document.getElementById("holy").value
      if (x == "mangos") {
        alert("Right Password!");
        window.location.replace("private.html");
        return false;
      }
      else {
        alert("Wrong Password!");
        window.location.replace("home.html");
        return false;
      }
    }