简体   繁体   中英

why my redirect code is not working but my alert is working ? please correct my code and check

Here is my code, this line window.location = "https://www.google.com"; is not working but the alert is fully working. Please help me. Thanks!

<!DOCTYPE html>
<html>
</html>
<head>
  <title>Document</title>
</head>
<body>
  <form>
    <label for="pswd">Enter your password: </label>
    <input type="password" id="myInput" autofocus>
    <input type="submit" id="myBtn" value="Submit" onclick="checkPswd();">
  </form>
  <script type="text/javascript">
    function checkPswd() {
      var confirmPassword = "admin";
      var password = document.getElementById("myInput").value;
      if (password == confirmPassword) {
        window.location = "https://www.google.com";
        // alert("correct");
      }
      else {
        alert("Password");
      }
    }       
  </script>
</body>        
</html>

The assignment to window.location triggers navigation but then the JS commpletes and the normal form submission continues which triggers navigation to the form's action (cancelling the previous navigation instruction).

You need to cancel the default behaviour.

Typically the approach to do that would be to bind an event listener to the submit event of the form (and not the click event of the button).

eg

function checkPswd(event) {
    event.preventDefault();
    // etc...
}

addEventListener('DOMContentLoaded'), () => {
    document.querySelector('form').addEventListener('submit', checkPswd);
});

Note, however, that any password system that involves asking the user's browser to authorise itself is pointless.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM