Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Last active January 16, 2024 01:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save WebReflection/15fc0a2bbdd5afc7a669 to your computer and use it in GitHub Desktop.
Save WebReflection/15fc0a2bbdd5afc7a669 to your computer and use it in GitHub Desktop.
Disable multile submits

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 ...
});
@jodydonetti
Copy link

This would leave out dynamically created elements and would not allow for inheritance of behaviours, like what we can do with css.
I'm not saying this is bad per se, just saying it should be done natively by the browsers.

@WebReflection
Copy link
Author

it would be nice to have it natively implemented ... meanwhile, it's a function, so you can always run it whenever you add a form dynamically ;-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment