Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery validate submits form twice

I'm using jQuery validator and jQuery 1.8.3. For some reason my form is submitted twice which causes errors. This is the code:

someNameSpace.myValidateFunction = function(){
    $('#myForm').validate({
        submitHandler: function(){
            mySubmitCallBackFunction();
        },
    });
    return false;
};

someNameSpace.myValidateFunction();
$(document).on('click', '#myFormSubmitButton', function(){
    $('#myForm').submit();
});

Any idea why the form is submitting twice? The form button is not an input submit but a <button> element (needed in this case).

like image 409
Weblurk Avatar asked Feb 12 '23 23:02

Weblurk


1 Answers

Your form is submitted twice because :

  • you call $('#myForm').submit()
  • you click on the submit button which also triggers the form event. Note : the , if it is in a form, will also trigger the form event on click

So I think you have to add a return false in your on click method to prevent the form to be submitted when you click on the submit button. Now, only $('#myForm').submit(); will submit the form :

someNameSpace.myValidateFunction = function(){
    $('#myForm').validate({
        submitHandler: function(){
            mySubmitCallBackFunction();
        },
    });
    return false;
};

someNameSpace.myValidateFunction();
$(document).on('click', '#myFormSubmitButton', function(){
    $('#myForm').submit();
    return false;
});

I think you also don't need to add this :

$(document).on('click', '#myFormSubmitButton', function(){
    $('#myForm').submit();
    return false;
});

The validate method will be automatically called when the form is submited.

like image 162
Lucas Willems Avatar answered Feb 16 '23 03:02

Lucas Willems