开发者

How can I ensure only one form submission, while playing nicely with jQuery validate?

开发者 https://www.devze.com 2023-02-26 05:54 出处:网络
I was using the following to disable all submit buttons on a form after it has been submitted, to prevent people double clicking submit buttons, etc:

I was using the following to disable all submit buttons on a form after it has been submitted, to prevent people double clicking submit buttons, etc:

jQuery (function ($) {
    $('form').bind ('submit', function () {
        $(this).find ('button').attr ('disabled开发者_JAVA百科', 'disabled');
    });
});

I am using jquery.validate, which in the event of a validation error, still fires off 'submit' when the form is submitted, and thus the user is left with a form with errors, and disabled submit buttons.

How can I modify the above code to detect if the form had jquery.validation errors?


$(function() {
    $('form').bind('submit', function() {
        $(this).find('input:submit').attr('disabled', true);
    });
});

You can check if the form is valid by calling $("form").valid()


Fire the validation manually in the submit button click event and return false; if there's an error to prevent the POST:

$('#submit').click(function(){ if(!validate()) return false; });

var validate = function() { if($('#txtFirst').val().trim() == '') return false;}
//etc...


I'd say that your bigger problem would be, "why is jQuery Validate throwing errors?" Solve that and you won't have to worry about this too much. Ideally, you should have this sort of thing run from the jQuery Validate Submit Handler.

http://docs.jquery.com/Plugins/Validation/validate#options

Once the validation runs, it calls the submitHandler for further processing.

$("#myForm").validate({
   submitHandler: function(form) {
    $(form).find ('button').attr ('disabled', 'disabled');
    $(form).submit();
   }
})
0

精彩评论

暂无评论...
验证码 换一张
取 消