Saturday, July 13, 2013

How to prevent user from double clicking button on a web application

I faced with situations where users click a button on a web application, and before the request was processed and response comes to the client user clicks again. This may produce inconsistent and unexpected results. A calculation will be performed twice or an entry is posted twice.
In order to prevent this I used was disabling the button until the response using java script.
I’m working with ASP.NET web application coded with C#.

·         First ‘OnClientClick‘ event is set to disable the button.
·         The ‘UseSubmitBehavior’ attribute is set to false, that will include the ‘OnClick’ event to _dopostbak script method rather than just submitting the page on button click

So the button would look like this
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" UseSubmitBehavior="False" OnClientClick="onclick=this.disabled=true;" />

The HTML output of it will render to something like this
<input name="Button1" id="Button1" onclick="onclick=this.disabled=true; __doPostBack('Button1','')" type="button" value="Button"/>

And that it the button is disabled onclick and will be enabled back on when the response comes.

You might get a script error if you use this on Internet Explorer 10 browser with .NET Framework 4. This is due to browser definition mismatch. You can fix this by installing the Hotfix provided here by Microsoft.

1 comment: