Disable an ASP.NET button after clicking
Posted
Friday, April 18, 2008 3:12 PM
by
Nathan Zaugg
I was creating a payment form recently and I wanted to disable the submit button after the user had clicked it so that there was no chance of them clicking it twice on accident.
This seems like one of those things that just ought to be a slam dunk! Back when I was doing ASP, this was one of the easiest things I ever did. I have done it with asp.net before, but I never needed validation to work as well. It took me a long time, many searches and trial and error but I found a solution that will disable the button and doesn't get in the way of validation.
protected override void OnInit(EventArgs e) { // We need this to get our button event Form.SubmitDisabledControls = true; btnProcessPayment.UseSubmitBehavior = false; // Attach javascript code to the OnClientClick event btnProcessPayment.OnClientClick = "javascript :if ( Page_ClientValidate() ) " + "{this.disabled=true; this.value='Please Wait...'};"; base.OnInit(e); }
The javascript is pretty straight-forward. We are simply calling the validation function ourselves, if it validated we disable the button and change the text. What does the rest of the code do then? Well, normally when a control is disabled it doesn't post data on postback. Fortunantly, ASP.NET makes it easy to override that default behavior. Without this data our button click event would never fire!
You can also do this in the HTML as well.
<form id="form1" submitdisabledcontrols="true" runat="server"> <asp:button id="btnProcessPayment" onclick="btnProcessPayment_Click" runat="server" onclientclick="javascript :if ( Page_ClientValidate() ) {this.disabled=true; this.value='Please Wait...'};" usesubmitbehavior="false" text="Process Payment" />
I hope this is useful to someone! If you end up using it on one of your sites, please leave a comment!