Home > Net >  window.location.href doesn't redirect unless document.write
window.location.href doesn't redirect unless document.write

Time:09-07

I just started JavaScript, and tried to make a site, that redirects me, when I enter the correct password. I tried to program it to redirect even when I press enter.

<!DOCTYPE html>
<html>
    <head>
        <title>P</title>
        <script type="text/javascript">
            function v() {
                const pw = document.getElementById('pwf').value;
                //document.write("something");
                if (pw=="Password") window.location.href = "http://google.com";
            }
        </script>
    </head>
    <body>
    <div>
    <form name="P" action="">
         <input type="text" id="pwf" name="pwf" onkeydown = "if (event.keyCode == 13) document.getElementById('enter').click();"><br>
         <input type="button" id="enter" value="ENTER" onclick="v(this);">
    </form>
    </div>
    </body>
</html> 

It doesn't work unless I uncomment the document.write("something"); line, and I don't understand why.

Google Chrome

CodePudding user response:

Below is the working tested code.

Why your redirect is not working. Form tag by defaults submits (redirects), when you keyin enter, via action attribute. So the page is reloaded in your case, where the document.location.href is not called.

The onsubmit is returned false, is the code to implement.

Your document.write has nothing to do here on the redirect.

<html>
    <head>
        <title>P</title>
        <script type="text/javascript">
            function v() {
                const pw = document.getElementById('pwf').value;
                // document.write("something");
                if (pw=="Password") window.location.href = "http://google.com";
            }

            function onKeydown(event){
                if (event.keyCode == 13) 
                document.getElementById('enter').click();
            }
        </script>
    </head>
    <body>
    <div>
    <form name="P" action="" onsubmit="return false;">
         <input type="text" id="pwf" name="pwf" onkeydown = "onKeydown(event)"><br>
         <input type="button" id="enter" value="ENTER" onclick="v(this);">
    </form>
    </div>
    </body>
</html> 
  • Related