Prevent double submission of forms in jQuery

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

    I ended up using ideas from this post to come up with a solution that is pretty similar to AtZako's version.

     jQuery.fn.preventDoubleSubmission = function() {
    
        var last_clicked, time_since_clicked;
    
        $(this).bind('submit', function(event){
    
        if(last_clicked) 
          time_since_clicked = event.timeStamp - last_clicked;
    
        last_clicked = event.timeStamp;
    
        if(time_since_clicked < 2000)
          return false;
    
        return true;
      });   
    };
    

    Using like this:

    $('#my-form').preventDoubleSubmission();
    

    I found that the solutions that didn't include some kind of timeout but just disabled submission or disabled form elements caused problems because once the lock-out is triggered you can't submit again until you refresh the page. That causes some problems for me when doing ajax stuff.

    This can probably be prettied up a bit as its not that fancy.

提交回复
热议问题