Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save athanasiosem/c2de676231ca28ea90a6 to your computer and use it in GitHub Desktop.
Save athanasiosem/c2de676231ca28ea90a6 to your computer and use it in GitHub Desktop.

Coming from this post, the solution is very simple and doesn't need jQuery.

This is the function that will disable multiple submits to any form that has such attribute

function disableMultipleSubmits() { // by Andrea Giammarchi - WTFPL
  Array.prototype.forEach.call(
    document.querySelectorAll('form[disablemultiplesubmits]'),
    function (form) {
      form.addEventListener('submit', this, true);
    },
    {
      // button to disable
      query: 'input[type=submit],button[type=submit]',
      // delay before re-enabling
      delay: 500,
      // handler
      handleEvent: function (e) {
        var button = e.currentTarget.querySelector(this.query);
        button.disabled = true;
        setTimeout(function () {
          button.disabled = false;
        }, this.delay);
      }
    }
  );
}

As example, this form will be affected

<!DOCTYPE html>
<form method="post" action="?" disablemultiplesubmits>
  <button type="submit">click me</button>
</form>

We can use that function as DOMContentLoaded listener in a script that is not async (deferred or just regular script on heead tag) or simply at the end of the body.

// at the end of the page
disableMultipleSubmits();

// or within a defer or a non async script
document.addEventListener('DOMContentLoaded', disableMultipleSubmits, false);

The function logic does not affect regular behavior, so we can easily add other listeners.

document.querySelector('form').addEventListener('submit', function (e) {
  e.preventDefault();
  // rest of the Ajax checks and stuff ...
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment