Prevent double submission of forms in jQuery

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

    In my case the form's onsubmit had some validation code, so I increment Nathan Long answer including an onsubmit checkpoint

    $.fn.preventDoubleSubmission = function() {
          $(this).on('submit',function(e){
            var $form = $(this);
            //if the form has something in onsubmit
            var submitCode = $form.attr('onsubmit');
            if(submitCode != undefined && submitCode != ''){
                var submitFunction = new Function (submitCode);
                if(!submitFunction()){
                    event.preventDefault();
                    return false;
                }                   
            }
    
            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);
            }
          });
    
          /*Keep chainability*/
          return this;
        };
    

提交回复
热议问题