The Empty Flask

Preventing multiple form submissions

My last post was a few months ago, so I suppose it's about time for a new blog entry...

I just had to fix a bug where users were clicking the submit button on a form up to 10 times before getting some sort of response, but since this is a form that is both loaded and submits via AJAX, the usual solutions aren't good enough. Here's a piece of code that works:

jQuery(document).ready(function($) {

  // Prevent multiple form submissions
  $("form").live("submit", function() {
    var form = $(this);
    form.find('input[type=submit]').attr('disabled', true);
    $.ajax({
      complete: function() {
        form.find('input[type=submit]').attr('disabled', false);
      }
    });
  });

});

If it's a typical HTML form, the submit button is disabled until a page load, but if the form was submitted asynchronously, it will only be disabled until a response is received. If you use this in your own web apps, you may want to change the 'complete' event to 'error' depending on what else your page does, but this works in my situation.

Update!

The above code breaks in IE, as disabling the submit button also prevents the form from being submitted at all. Here's something that works for that screwed-up browser:

jQuery(document).ready(function($) {

  // Prevent multiple form submissions
  $("form input[type=submit]").live("click", function() {
    var submit = $(this);
    var original_val = submit.val();
    submit.bind('click.deny', function(){ return false; }).val('Please wait...');
    submit.ajaxComplete(function() {
      submit.val(original_val).unbind('click.deny');
    });
  });

});

Categories

Other Posts

RSS Feed

Subscribe

Archives