Prevent double submission of forms in jQuery

后端 未结 22 1341
旧时难觅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:25

    Modified Nathan's solution a little for Bootstrap 3. This will set a loading text to the submit button. In addition it will timeout after 30 seconds and allow the form to be resubmitted.

    jQuery.fn.preventDoubleSubmission = function() {
      $('input[type="submit"]').data('loading-text', 'Loading...');
    
      $(this).on('submit',function(e){
        var $form = $(this);
    
        $('input[type="submit"]', $form).button('loading');
    
        if ($form.data('submitted') === true) {
          // Previously submitted - don't submit again
          e.preventDefault();
        } else {
          // Mark it so that the next submit can be ignored
          $form.data('submitted', true);
          $form.setFormTimeout();
        }
      });
    
      // Keep chainability
      return this;
    };
    
    jQuery.fn.setFormTimeout = function() {
      var $form = $(this);
      setTimeout(function() {
        $('input[type="submit"]', $form).button('reset');
        alert('Form failed to submit within 30 seconds');
      }, 30000);
    };
    

提交回复
热议问题