Naomi Naomi - 2 months ago 24
jQuery Question

Route to another page onsubmit

I am trying to create a login page in javascript. When the right user types in the right username and password it should take them to another page. I can't seem to find a way for the new page to load.

This is my html

<body>
<form name="myForm" onsubmit="return validation()" method="post">
User name:
<br>
<input type="text" name="userid">
<br> User password:
<br>
<input type="password" name="password">
<input type="submit" value="Submit" id="login">
</form>
</body>


and this is my JS

function validation() {
var x = document.forms["myForm"]["userid"].value;
var y = document.forms["myForm"]["password"].value;
if (x == "Naomi" && y == "Amaze") {
alert("RIGHT password");
return true;
window.location.href = "budget/index.html";
} else {
alert("Wrong password");
return false;
};


}


The alerts work so I am suspecting that window.location.href isn't the correct way of doing it.

Answer

Anything that goes after the return statement will not be executed. A return is an exit door from your function so leave it as the last instruction.

Additionnally I would add that hopefully the credential testing isn't done in the client-side JavaScript code or else it would be easy for anyone to inspect your code and find the real credentials.

Last thing : I usually tend to add a listener on the submit event of a form instead of ask it to return the result of a function. I can't say for sure why it is better, it just sounds more accurate to me :

<body>
       <form name="myForm" id="myForm" method="post">
        User name:
        <br>
        <input type="text" name="userid">
        <br> User password:
        <br>
        <input type="password" name="password">
        <input type="submit" value="Submit" id="login">
    </form>
</body>
// ...
<script type="text/javascript">
    document.getElementById('myForm').addEventListener('submit', function(event){
        // this line prevents the normal behaviour of the form (ie: reloading the page with form data sent as POST data)
        event.preventDefault();

        // now we can check the form data
        var x = this.userid.value;
        var y = this.password.value;
        if (x == "Naomi" && y == "Amaze") {
            alert("RIGHT password");
            window.location.href = "budget/index.html";
        } else {
            alert("Wrong password");
        };
    });
</script>
Comments