1

So I have been working on this little puzzle site and I want the correct password for the textfield to be inside the JS function. Now it does recognize the password already which is good but the issue is that when I try to use window.location.href = "https://www.google.com"; it does not redirect the page to new site. It only "refreshes" the site..

My script is as followed:

<script>
    function validate() {
        var password = document.forms["passwordform"]["password1"].value;
        var realpassword = 'salaisuus'
        if (password === realpassword) {
            window.location.href = "http://www.google.com";
            return true;
        } else {
            alert("Wrong password")
            return false;
        }
    }
</script>

and the actual form is here:

<form id="passwordform" onSubmit="return validate()">
    <div class="form-floating mb-3">
        <input type="text" class="form-control" id="floatingInput" name="password1" placeholder="whatwhat">
        <label for="floatingInput">PASSWORD</label>
    </div>
    <button type="submit" class="btn btn-dark">TRY IT</button>
</form>

So as said, it does send the alert for wrong password, but the window.location.href is not working. What am I missing here?

newbNox
  • 1,000
  • 2
  • 15
  • 25
  • 1
    [here](https://stackoverflow.com/q/15759020/14834893) is the answer to your question. It says to `return` false after `window.location.href`. – M.Hassan Nasir Jun 08 '21 at 05:28
  • 2
    Immediately after setting the location you're returning true, which submits the form. This reloads the page because the form has no `action` attribute. You also need `https:` It's also better to assign an event listener in your JS code and prevent the submission event, as mentioned [here](https://stackoverflow.com/questions/67881757/how-do-i-get-and-print-a-variable-stored-in-localstorage-with-a-post-request#comment119983683_67881757) –  Jun 08 '21 at 05:30
  • Thank you all, I just figured it out.. I feel stupid now :D – newbNox Jun 08 '21 at 05:33
  • To echo @Chris G `https:` please ;) – Steve Jun 08 '21 at 05:34
  • This question is a duplicate, so no need to post an answer. –  Jun 08 '21 at 05:34
  • Duplicate: [window.location.href not working](https://stackoverflow.com/questions/18300674/window-location-href-not-working) –  Jun 08 '21 at 05:35

1 Answers1

0

www.stackoverflow.com/q/15759020/14834893 here is the answer of your question. – M.Hassan Nasir

Okey, so being little dummy...

All I need to do is add return false; after window.location.href

Thank you

newbNox
  • 1,000
  • 2
  • 15
  • 25