How to disable an ASP.NET button when clicked

Scenario: user clicks a button in your ASP.NET page and you want to disable it immediately using javascript so that the user cannot accidentally click it again. 

Originally I thought this was going to be simple by using the onclientclick property of the ASP.NET button server control but although that worked to disable the button, it did not continue with the form postback.  Eventually after quite a bit of Googling and some more failed attempts I figured out this solution:

MyButton.Attributes.Add("onclick", "this.disabled=true;" + Page.ClientScript.GetPostBackEventReference(MyButton, "").ToString());

Adding the javascript to disable the button to the onclick event by appending to the Attributes collection of the ASP.NET button control but then also calling the Post Back Event Reference for the button right after disabling the button.  That is why my original try at adding the javascript failed, adding the this.disabled=true to the onclientclick event then overwrote the call to the post back event. 

With the code above now the button onclick event will look something like this:


The button is disabled AND then the button post back method is called.

Technorati Tags: ,

Published 06 October 2009 09:32 PM by Jeff Widmer
Filed under: ,


# gt1329a said on 06 October, 2009 09:47 PM

You can avoid the GetPostBackEventReference, by setting the Button's UseSubmitBehavior to false.  That will automatically inject an appropriate __doPostBack().

See this for more info:

# vikram said on 07 October, 2009 06:43 AM


Why not use the onclientclick to add the javascript

MyButton.OnClientClick = "this.disabled=true;";

# Jeff Widmer said on 07 October, 2009 06:57 AM

Hi Vikram,

That is what I initially tried but then the button did not postback because the postback event is overwritten.  So you need to add the postbackevent to the onclick like I did in the code behind or use gt1329a's solution which is to set the UseSubmitBehavior property to false.


# George said on 09 October, 2009 09:50 PM

Thank you so much. I think this fix can also be used when showing/hiding div statements in javascript when a button is clicked.

# tarjeta nintendo r4 said on 12 October, 2009 03:00 AM

It is useful. But i am not interest in Java script. I am always confuse with Java script. but anyways thanks for sharing information.

# tperri said on 12 October, 2009 02:00 PM

tarjeta, you should be interested in Javascript if you are a web developer, regardless if it confuses you or not.

Unconfuse yourself and do some studying.

Just sayin'.

Thanks for the post, Jeff

# anon said on 28 January, 2010 05:04 PM

this disables my requiredfieldvalidators



This Blog