Assume you got this form


  <form action="/insert_2000_rows_now" method="POST">
    <button>Submit<button> 
  </form>

which inserts on submits 2000 rows. It could happen that on double click 4000 rows are inserted. That is bad.

At the backend you always have to care for parallel calls and raising conditions. However on the front-end you don’t, because JS is procedural. Thus, if one simply disables the button on submit, the user can’t submit twice (unless he disables JS).

A good idea is this piece of code:


$('form').submit(function(){
  $(this).find(':submit').attr('disabled','disabled');
});

Make sure to disable the button on submit instead of click, because the form could have multiple buttons or it could be submitted by customized JS code.

Remember, in Firefox when you disable a button this state will be remembered when you go back in history. To prevent that you have to enable buttons on page load, for example.

Also note, that the above example will only help for the cases where you have a plain form. If you have something fancy like an ajax call when hitting the button, then you should disable the button on the buttons call


$('#pushMe').click(function(){
  $(this).attr('disabled','disabled');

  $.ajax(...)
});

Also note, if you create dynamical buttons, then they are not effected by `$(…).click()` – this only effects buttons that have been there since the beginning of the page. Instead we should find a closest HTML parent of all the buttons with a common class (this might be the `$(document)` itself, but its a good idea not to bloat the main document with listeners).

For dynamical buttons that are all inside of div with id `wrapper` and do something like an ajax call, we could use this to disable them:


$('#wrapper').on('click', '.dynamicButt',function(){
  // only disable clicked button:
  $(this).attr('disabled','disabled');

  // if you want to disable all buttons of this class
  // use this instead:
  // $('#wrapper .dynamicButt').attr('disabled','disabled');
  $.ajax(...)
});

Another way of solving this is by creating a jQuery plugin that you call on a form whenevery you want to prevent doubleclick: https://stackoverflow.com/a/4473801

adam