Advantages
- Works out of the box for all buttons
- Even buttons that did not trigger the submit will be disabled.
- LinkButtons will also be disabled.
- Works with UpdatePanels (ie, partial and asynchronous postbacks)
- Works for full postbacks
- Won't disable buttons when validation prevents postback
- Button press, enter-key press and AutoPostBack events will cause buttons to become disabled
Limitations
† Most other solutions I have seen have these same limitations
- Relies on jQuery
- † Only works for ASP forms
- † If the user clicks the browser's cancel button after submission, the user will not be able to submit again and may get confused.
- † There remains other ways that a user could initiate a postback:
- Submit using the enter key
- Autopostback events
Code
Simply place this snippet at the bottom of your HTML code before the closing </body>
tag.
<script type="text/javascript">
jQuery(function ($) {
/*
* Prevent Double Submit
* ---------------------
* Disables submit buttons during form submission and asp async postbacks
*/
// class name assigned to disabled :submit elements
var disabledClass = 'asp-postback-disable';
// selector for buttons and other elements that may cause a postback
var submittableSelector = [
'a[href^="javascript:__doPostBack"]',
':submit'
].join(",");
// returns false; used to prevent event bubbling
function returnFalse() { return false; }
// logs errors
function error(ex) {
if (typeof console === 'object' && console.error != null) {
console.error('Prevent Double Submit Error:', ex);
}
}
// disables :submit elements
function disableSubmit() {
try {
$(submittableSelector, 'form')
.addClass(disabledClass)
.on('click.asp-postback-disable', returnFalse);
}
catch (ex) { error(ex); }
}
// enables :submit elements
function enableSubmit() {
try {
$('.asp-postback-disable,' + submittableSelector, 'form')
.removeClass(disabledClass)
.off('click.asp-postback-disable', returnFalse);
}
catch (ex) { error(ex); }
}
// Handle async postbacks
if (typeof Sys === 'object') {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(function (s, e) { disableSubmit(); });
prm.add_endRequest(function (s, e) { enableSubmit(); });
}
else {
error('Sys is undefined.');
}
// Handle navigation (eg, Full postback)
$(window).bind('beforeunload', function (e) {
disableSubmit();
});
});
</script>
<style type="text/css">
.asp-postback-disable { opacity: 0.25; }
</style>