Search code examples
javascriptjqueryajaxjavascript-objectsjquery-events

Form submit after preventDefault not working until click submit button


I have a Login form that working fine. I tried to extend login action for adding extra features. First I prevent the form to be submit when the submit button is clicked, I perform ajax request and finally if everything is correct I submit the form, but my form is not submitted until the submit button is clicked twice. What am I doing wrong?

HTML Part:

<div id="loginFormDiv">
   <form class="form-horizontal" method="POST" action="index.php">
      <input type="hidden" name="module" value="Users">
      <input type="hidden" name="action" value="Login">
      <div class="group"><input id="username" type="text" name="username" ><span class="bar"></span><label>Username</label></div>
      <div class="group"><input id="password" type="password" name="password" ><span class="bar"></span><label>Password</label></div>
      <div class="group"><button type="submit" class="button buttonBlue">Sign in</button></div>
   </form>
</div>

JS Part:

jQuery.Class("ParsSecureLogin_Js", {}, {
    checkLogin: function () {
        var thisInstance = this;
        var checkUserLogin = function (e) {
            e.preventDefault();
            var username = $('#username').val();
            var user_pass = $('#password').val();
            var theForm = $(this);
            var url = 'index.php?module=ParsSecureLogin&parent=Settings&action=CheckLogin&_user=' + username + '&_pss=' + user_pass;
            jQuery.ajax({
                url: url
            }).done(function (data) {
                if (data == '' || data == 'undefined') {
                    alert('Unknown error. Please contact admin to check!');
                    return false;
                } else {
                        theForm.unbind('submit').submit();
                        return true;
                }
            });
        }
        jQuery('#loginFormDiv').on("submit", checkUserLogin);
    },
    registerEvents: function () {
        var thisInstance = this;
        thisInstance.checkLogin();
    }

});

jQuery(document).ready(function () {
    var ParsSecureLogin = new ParsSecureLogin_Js();
    ParsSecureLogin.registerEvents();
});

Solution

  • It is because #loginFormDiv is a <div> not a <form> change the selector to:

    jQuery('#loginFormDiv form').on("submit", checkUserLogin);