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: ,


  • 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:

  • Hi,

    Why not use the onclientclick to add the javascript
    MyButton.OnClientClick = "this.disabled=true;";

  • 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.

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

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

  • 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

  • this disables my requiredfieldvalidators

Add a Comment

As it will appear on the website

Not displayed

Your website