Prevent double submission of forms in jQuery

后端 未结 22 1371
旧时难觅i
旧时难觅i 2020-11-22 08:10

I have a form that takes a little while for the server to process. I need to ensure that the user waits and does not attempt to resubmit the form by clicking the button agai

22条回答
  •  长发绾君心
    2020-11-22 08:42

    Nathan's code but for jQuery Validate plugin

    If you happen to use jQuery Validate plugin, they already have submit handler implemented, and in that case there is no reason to implement more than one. The code:

    jQuery.validator.setDefaults({
      submitHandler: function(form){
        // Prevent double submit
        if($(form).data('submitted')===true){
          // Previously submitted - don't submit again
          return false;
        } else {
          // Mark form as 'submitted' so that the next submit can be ignored
          $(form).data('submitted', true);
          return true;
        }
      }
    });
    

    You can easily expand it within the } else {-block to disable inputs and/or submit button.

    Cheers

提交回复
热议问题