Skip to content

Instantly share code, notes, and snippets.

@floko84
Last active November 28, 2018 09:33
Show Gist options
  • Save floko84/d5484d938d9a06a329dd756e90cb94ce to your computer and use it in GitHub Desktop.
Save floko84/d5484d938d9a06a329dd756e90cb94ce to your computer and use it in GitHub Desktop.
jQuery plugin to prevent multiple HTML form submits. With support for custom validator logic, custom submit action, as well as a timeout to re-enable submits. Submit buttons are disabled for UI feedback.
/*
jQuery Prevent Double Submit Plugin by Florian Kollmann <floko84@gmail.com>
*/
; (function ($) {
"use strict";
var pluginName = "preventDoubleSubmit",
defaults = {
valid: function () {
// run jQuery validate if available
return !$.isFunction($.fn.valid) || $(this).valid();
},
submit: $.noop,
timeout: Number.POSITIVE_INFINITY,
};
function Plugin(element, options) {
this.element = element;
this.settings = $.extend({}, defaults, options);
this.init();
}
$.extend(Plugin.prototype, {
init: function () {
this.submitted = false;
this.buttons = [];
this.delay = 250;
$(this.element).submit($.proxy(this.onSubmit, this));
},
onSubmit: function (event) {
if (this.submitted) {
// block multiple submits
return false;
}
if (!this.isValid()) {
// allow validators to run
event.preventDefault();
return true;
}
var result = true;
if ($.isFunction(this.settings.submit)) {
// call submit handler, if any
result = this.settings.submit.call(this.element, event);
}
this.disable();
return result;
},
disable: function () {
this.submitted = true;
this.buttons = $(this.element).find('[type="submit"]').not(':disabled');
window.setTimeout($.proxy(function () {
$(this.buttons).prop('disabled', true);
if ($.isNumeric(this.settings.timeout)) {
window.setTimeout($.proxy(this.enable, this), this.settings.timeout);
}
}, this), this.delay);
},
enable: function () {
this.submitted = false;
$(this.buttons).prop('disabled', false);
},
isValid: function () {
return !$.isFunction(this.settings.valid)
|| this.settings.valid.call(this.element);
},
});
$.fn[pluginName] = function (options) {
return this.each(function () {
if (!$.data(this, "plugin_" + pluginName)) {
$.data(this, "plugin_" +
pluginName, new Plugin(this, options));
}
});
};
$(function () {
// auto-load for class
$('form.prevent-double-submit')[pluginName]();
})
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment