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?

6
  • 2
    here is the answer to your question. It says to return false after window.location.href. Commented Jun 8, 2021 at 5: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 Commented Jun 8, 2021 at 5:30
  • Thank you all, I just figured it out.. I feel stupid now :D Commented Jun 8, 2021 at 5:33
  • To echo @Chris G https: please ;) Commented Jun 8, 2021 at 5:34
  • This question is a duplicate, so no need to post an answer. Commented Jun 8, 2021 at 5:34

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.