Georgi  Stoyanov
Georgi Stoyanov

Reputation: 539

jQuery/JS won't redirect after validation of form

I'm trying to validate a password from a form using jQuery/JavaScript. Post-validation, I want the script to redirect me. However, this isn't currently working.

Note: this is only an exercise from my university, so that's why the code is very simple:

HTML:

!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="js/passwordCheck.js"></script>
</head>
<body>
  <form method="post" name="form1" id="form-password" action="">
    <label>Password:</label>
    <input type="password" name="password" id="password" value="" size="32" />
    <input type="submit" value="Continue" id="submit">
  </form>
</body>
</html>

JS/jQuery:

'use strict';
jQuery(document).ready(function($) { 
    $('#form-password').submit(function() { 

        var passwordVal = $('#password').val();

        if (passwordVal === "123" ) {
            $(location).attr('href', 'http://www.stackoverflow.com'); 
        }   

    });
});

I tried:

window.location.href = "http://www.stackoverflow.com";

but that doesn't work either.

I know that I need to check the submitted data, my problem is only with redirection.

How can I fix this?

Upvotes: 1

Views: 296

Answers (2)

justinledouxweb
justinledouxweb

Reputation: 1357

You simply need to preventDefault() inside your submit listener, and then call

window.location.href = "...";

Currently, without preventing the default action of submitting a form, the form tries to POST your data, regardless of what happens in the submit callback.

If you preventDefault, the form will not submit until you return true.

That being said, redirects should be performed on the backend or by the front-end MVC framework. In any way, the password data needs to be submitted and checked against a database somewhere.

Upvotes: 2

Jeff Voss
Jeff Voss

Reputation: 3695

Try this, you are modifying the window.location.href property, you really want to be setting the window.location like this:

$('#form-password').submit(function(e) {
    e.preventDefault();

    var passwordVal = $('#password').val();

    if (passwordVal === '123') {
        window.location = 'http://www.stackoverflow.com';
    }

});

Upvotes: 2

Related Questions