Author:
Joe Hakooz
Category:
ASP.NET
Real quick post here regarding an annoying behavior with the ASP.NET submit button and a simple fix...
Maybe it's by design, but users can easily double click a submit button causing the page to postback twice (or more). This may cause issues particularly if you are inserting records into a database.
To fix this, I created a few lines of JavaScript and JQuery which will do a few things:
- Immediately disable the button so multiple clicks cannot occur.
- Change the button text to let the user know something spectacular is about to happen.
- Respect form validationgroup if applicable.
First add this JavaScript to your site...
// Submit Once
function submitOnce(myButton, txt, validationgroup) {
// Client side validation
if (typeof (Page_ClientValidate) == 'function') {
if (Page_ClientValidate(validationgroup) == false) {
return false;
}
}
$(myButton).attr('disabled', 'disabled');
$(myButton).val(txt);
return true;
}
Next, add this onClientClick attribute to your asp:button.
<asp:Button id="Button1" runat="server" Text="Save Changes" onclick="Button1_Click"
OnClientClick="submitOnce(this,'Saving...','');"
UseSubmitBehavior="false" CausesValidation="true" />
Important Note: I don't remember for sure but I think you also need to include the UseSubmitBehavior="false" and CausesValidation="true or false" depending on if you need to validate.
Notice that the submitOnce function takes three parameters.
1: The button or: this
2: Button text to show after the click.
3. Optional ValidationGroup name.
That's it! Your button is now protected from double clicks!
Feel free to tweak the above code and make it more flexible, but this does the trick for me...