'Issue in html code for redirect user to url after is logged

Hi I’m html learner and I have an issue with my code but I don’t know what’s the problem

The prob is weird , when i enter the right pass in only have my alert « Le mot de passe est correct » but the page is just reload and not move to https://mycool-url.com

This is a simple html code it’s for learn password

  <title>Authentification</title>
</head>

<body>
  <div class="main">
    <p class="sign" align="center">Veuillez vous identifier</p>
    <form class="login">
      <input class="pass" type="password" align="center" id="password" placeholder="Mot de Passe" type="password" name="pswrd">
      <input class="submit" align="center" type="submit" onclick="checkPassword()" value="Login" />
    </form>
  </div>

  <script>
    function checkPassword() {
      if (document.getElementById('password').value == 'ZhFAIHhyRvBaZ') {
        alert('Mot de passe correct')
        location.replace('https://www.mycool-url.com');
      } else {
        alert('Mot de passe incorrect');
        return false;
      }
    }
  </script>
  </script>
</body>


Solution 1:[1]

The form is submitting. If you don't want to submit a form, change the button type from type="submit" to type="button":

<input class="submit" align="center" type="button" onclick="checkPassword()" value="Login" />

If you're not using a "form" at all, you can even just remove the <form> element entirely, which would prevent accidental form submission.

As an aside, it's also worth noting that any user can see the "password" or go directly to the target URL so this authentication mechanism doesn't secure anything.

Solution 2:[2]

The form is submitting each time. If you don't want to submit the form, you can use the following things for prevent form submission in your cause.

  1. <input class="submit" align="center" type="submit" onclick="checkPassword(); return false;" value="Login"/>
    
  2. Change the javascript function checkPassword() to return false all the time.

     function checkPassword(){
      if(document.getElementById('password').value == 'ZhFAIHhyRvBaZ'){
        alert('Mot de passe correct');
        window.location.href='https://www.mycool-url.com';
    
      } else {
        alert('Mot de passe incorrect');
        return false;
     }
      return false;
    }
    

and call it in onclick like this onclick="return checkPassword();"

 <input class="submit" align="center" type="submit" onclick="return checkPassword()" value="Login"/>

It will also prevent the form from submitting.

Solution 3:[3]

Replace location.replace('https://www.mycool-url.com'); by window.location.replace("https://www.mycool-url.com");

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 David
Solution 2 Vishnu S Vyshakh
Solution 3 Kip