Aaron Rotem Aaron Rotem - 5 months ago 16
Javascript Question

Issue redirecting to a new page in Javascript

I am new to JavaScript and am trying to compare two input fields before going to another page. The goals is that when a button is clicked the text from two input fields is compared and then the page is redirected to another page. I have tried using

window.location.href
as well as
window.location.replace
but so far nothing has worked. The redirect should be executed because the alert in the same block of logic is being executed. Thank you for any advice/help.

<html>

<head>
<script type="text/javascript">
function sub(){
if(document.getElementById("p1").value == document.getElementById("p2").value){
alert("success");
window.location.replace="http://localhost:8080/newUser.php";
} else {
alert("Password do not match");
}
}
</script>
</head>

<body>
<form onSubmit="sub()" method="post">
Password: <input type="text" id="p1" name="password"><br>
Confirm Password: <input type="text" id="p2" name="passwordConfirm"><br>
<input type="submit">
</form>
</body>

</html>

Answer

Here is how you can do it. You must return false in your function to prevent your form to be posted; now you have onsubmit="return sub();" in your form.

<html>

    <head>
        <script type="text/javascript">
            function sub(){
                if(document.getElementById("p1").value == document.getElementById("p2").value){
                    alert("success");
                    window.location.href=  "http://localhost:8080/newUser.php";
                } else {
                    alert("Password do not match");
                }
		return false; // IMPORTANT RETURN STATEMENT
            }
        </script>
    </head>

    <body>
        <form onSubmit="return sub();" method="">
          Password: <input type="text" id="p1" name="password"><br>
          Confirm Password: <input type="text" id="p2" name="passwordConfirm"><br>
          <input type="submit">
        </form>
    </body>

</html>

Now if you want to post the typed parameters (password and passwordConfirm) to this page then @musicfuel's answer is almost correct, you should just add onsubmit="return sub();" instead of onsubmit="sub()"