Decrease Font Size
Increase Font Size

Disable an ASP.NET button during PostBack with AJAX loading background image

Disable submit button after user click | Disabling an ASP.NET Button when Clicked | Disable an ASP.NET button after clicking | Page_IsValid is undefined - JavaScript error message

Disable an ASP.NET button during PostBack with AJAX loading background image


There are times when our applications might take an extra few seconds to respond to a click event. Some users might get impatient and click on the button more than once. We can easily avoid this type of situation by disabling the submit button during PostBack on the page by using a client side script. In this article, I will share with everyone on how to:

  1. Disable the button during PostBack with or without the present of validation control

  2. Change the button text value during PostBack

  3. Include an AJAX loading background image during PostBack

  4. How I avoided the 'Page_IsValid is undefined' JavaScript error

Before we begin, allow me to show you the structure of my project. You are welcome to download this demo.

 Projext structure
Demo 1 – Without Validation Control

Here is the content of the Jscript.js

function disableBtn(btnID, newText) {

    var btn = document.getElementById(btnID);
        setTimeout("setImage('"+btnID+"')", 10);
        btn.disabled = true;
        btn.value = newText;

function setImage(btnID) {
    var btn = document.getElementById(btnID); = 'url(12501270608.gif)';

Here is part of the Default.aspx page content.

                     <asp:button id="btnOne" tabIndex="0" Runat="server" Text="Submit"
                        OnClientClick="disableBtn(, 'Submitting...')" 
                        UseSubmitBehavior="false" />               
                <td colspan="2">
                    <asp:Label ID="Label3" runat="server" Text=""></asp:Label></td>

<script type="text/javascript" src="JScript.js"></script> 

In this page, I have a button and a label control. Let take a closer look at the button attributes.

OnClientClick="disableBtn(, 'Submitting...')" - Calls the JavaScript function by passing in the button ID and the new text value that I want it to display on click.

UseSubmitBehavior="false" - Indicates that the button control should use the ASP.NET postback mechanism instead of client browser's submit mechanism ( UseSubmitBehavior Property )

For testing, I included these lines in the default.aspx.cs

protected void btnOne_Click(object sender, EventArgs e)
        Label3.Text = DateTime.Now.ToLongTimeString();

Here how's the button will look like when someone click on it.

 on click Demo 1 Output

Demo 2 – With Validation Control

Here is the output from Default2.aspx

 Demo 2 aspx page

Ops... The button is still disabled after it failed the validation process. Let modify the JavaScript to fix this problem.

 Demo 2 aspx page 2

Here is the content of the new JavaScript with comments– Jscript2.js 08/14/2009 - I found out that, in Firefox, if we hit the button and continue to the next page, and then hit the back button (or javascript:history(-1);)... the button control is still disabled. I have updated the JavaScript(JScript2) to enable the button onunload for browser other than IE

10/12/2009 - I have updated the JavaScript(JScript2) to prevent double validation.

11/14/2009 - Fix bug mentioned by CodeProject user, prodriguez13. The JavaScript will throw an error when the control to validate is not visible. To remedy this problem, I have added DisableValidators function and trigger it on onload event. This function is responsible to disable all the validators where controltovalidate is null.
* I have received several requests on getting this script to work with Image button. I managed to put together a solution for it. Let me know if you find any bugs.
* Tested on IE 7.0/8.0, FireFox, image is not showing on Google Chrome, maybe someone can shed some light on this.

function ResetToDefault(btn, oldValue) {
    btn.disabled = false;
    btn.value = oldValue;
//browser properties
var Browser = {
    Version: function() {
        var version = 999;
        if (navigator.appVersion.indexOf("MSIE") != -1) {
            version = parseFloat(navigator.appVersion.split("MSIE")[1]); return version;
    Name: navigator.appName,
    isIE: function() {
        if (navigator.appVersion.indexOf("MSIE") != -1) {
            return true;
        return false;

//Handle Page_Validators is not defined error
function HasPageValidators() {
    var hasValidators = false;
    try {
        if (Page_Validators.length > 0) {
            hasValidators = true;
    catch (error) { }

    return hasValidators;

function SetImage(btn) {

    if (btn.type == "image") {
        btn.src = null; = '100px'; = '20px'; = 'url(';
    else {
        //somehow backgroundImage not working with IE 7
        if (Browser.isIE() && Browser.Version() === 7) {
   = 'url(';
        else {
   = 'url(';

//enable the button and restore the original text value for browsers other than IE
function EnableOnUnload(btn, btnText) {
    if (!Browser.isIE()) {
        window.onunload = function() {
            ResetToDefault(btn, btnText);

//check if the validator have any control to validate
function EnableValidator(validator) {
    var controlToValidate = document.getElementById(validator.controltovalidate);

    if (controlToValidate !== null) {
        // alert(;
        return true;
    ValidatorEnable(validator, false);

    return false;

function disableBtn(btnID, newText) {
    var btn = document.getElementById(btnID);
    var oldValue = btn.value;
    btn.disabled = true;
    btn.value = newText;
    //if validator control present
    if (HasPageValidators()) {

        Page_IsValid = null;

        //double check, if validator not null
        if (Page_Validators !== 'undefined' && Page_Validators !== null) {
            //Looping through the whole validation collection.
            for (var i = 0; i < Page_Validators.length; i++) {

                var validator = Page_Validators[i];

                //check if control to validate is enable 
                if (EnableValidator(validator)) {

                    if (!Page_Validators[i].isvalid) { //if not valid
                        ResetToDefault(btn, oldValue); //break;

            //   else { //if valid
            var isValidationOk = Page_IsValid;

            alert('isValidationOk ' + isValidationOk);

            EnableOnUnload(btn, btn.value);
            if (isValidationOk !== null) {
                if (isValidationOk) {
                    __doPostBack(btnID, '');
                    // break;
                else { //page not valid
                    btn.disabled = false;
            //  }
    else { //regular, no validation control present
        // setTimeout("SetImage('" + btn + "')", 5);
        btn.disabled = true; btn.value = newText;
        EnableOnUnload(btn, btn.value);

//disable those validators where controltovalidate = null
function DisableValidators() {
    //this will get rid of the Page_Validators is undefined error
    if (typeof (Page_Validators) === 'undefined')
    if (Page_Validators !== 'undefined' && Page_Validators !== null) {
        for (var i = 0; i < Page_Validators.length; i++) {
            var validator2 = Page_Validators[i];
            var controlToValidate2 = document.getElementById(validator2.controltovalidate);
            if (controlToValidate2 === null) {
                ValidatorEnable(validator2, false);
    return false;

window.onload = DisableValidators;

Output using the new JavaScript

 Demo 2 aspx page 2  Demo 2 aspx output 3
 Demo 2 aspx output 4


The main items in this project were the JavaScript (Jscript2) and the button attributes (OnClientClick, UseSubmitBehavior)

I hope someone will find this tutorial useful. If you think I still can improve this code, please leave me a feedback and share your thought.

Tested on IE 6.0/7.0 and Firefox 3.0.2

Watch this Script in action

Comments (55) -

  • Интернет Маркетинг

    7/30/2009 8:08:06 AM |

    Thanks mate!I was looking for that solution nearly all day!I love your blog,awesome!!!
    Can I copy this article on my blog?If,yes we can exchange useful articles in the future?

  • best

    9/3/2009 8:33:57 AM |


  • Stephen Dale

    9/4/2009 8:01:18 AM |

    You can also use the following in the code behind without javascript.

    var clickHandler12 =
                            " = 'wait'; this.value='Please Wait...'; this.disabled = true; {0};",
                            ClientScript.GetPostBackEventReference(_btnIncludeWriteGroup, string.Empty));

    _btnSomeButton.Attributes.Add("onclick", clickHandler12);

  • Thanigainathan

    9/4/2009 2:07:40 PM |


    I expected somewhat more than you have written. I thought you are going to tell about Ajax.
    Can you please throw some light on this stuff with Ajax.


  • Ravi

    9/5/2009 4:27:04 PM |

    can we do the same for image button....


  • Ravi

    9/6/2009 2:53:07 PM |

    No i dont have as sach code but im using image button in my project.

  • Adeel Alvi

    9/14/2009 8:11:17 AM |

    There is one issue while using your code , as i have some RequiredFieldValidator which are disabled on PageLoad and will enable on some option clicked by user , but after using your code it asked for those RequiredFieldValidator as well that are disabled on Page Load.

  • bryian

    9/17/2009 11:35:10 PM |

    Hello, I have updated the script and source code.

  • Outsourcing

    9/30/2009 12:15:38 AM |

    I was just thinking about Disable an ASP.NET button during PostBack with AJAX loading background image and you have really helped out. Thanks!

  • Hopeto

    10/12/2009 7:15:50 AM |

    Thanx for the article. i was searching the same functionality for an image button. will try it out.

  • ditte traslochi milano

    10/12/2009 10:09:24 AM |

    That's great, I never thought about Disable an ASP.NET button during PostBack with AJAX loading background image like that before.

  • Craft Shows

    10/20/2009 12:46:00 AM |

    That's great, I never knew before this blog.

  • Craft Fairs

    10/20/2009 4:53:07 AM |

    That's really very nice blog, I am impressed.

  • Deals

    11/28/2009 7:40:27 AM |

    love this post.
    Thanks frenz.
    dont stop posting!

  • Cross Stitching

    12/15/2009 12:11:11 PM |

    Wow, thanks for a great tutorial on disabling the button with ajax during postback. Very useful and very detailed.

  • P90X

    12/16/2009 1:41:57 AM |

    I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts.
    I will catch up your updates in future.

  • Internet Marketing Italy

    12/16/2009 3:40:38 AM |

    This is the good step u have taken. Thanks for writing this, its clear you have spent a good amount of time on your sites development.

  • NOD32

    12/20/2009 6:41:20 AM |

    Hey saw your post today & bryianI must say you have done a great job in understanding the basics of this topic & working on the updates. I am looking forward to more articles from you on the same topic.

  • ESET

    12/22/2009 7:45:07 AM |

    Thanks a lot for the post. Your views are rally insightful and am looking forward to read more from you. Thanks

  • Statistics Help

    12/28/2009 11:48:50 PM |

    Great work dude, u gave nice post to us. Thanks for spending the time to discuss this, I feel strongly about it and love learning more on this topic.

  • Kerala Tourism

    12/29/2009 3:36:28 AM |

    This is a great and very valuable information about Disable an ASP.NET button during PostBack with AJAX loading background image. Thank you very much for sharing this information with us.


  • japan

    1/2/2010 12:50:48 AM |


    How do you deduct proffessional tax from your Gross salary in ITR 2 ? In which Schedule?

  • Wooden Doors

    1/6/2010 11:01:43 AM |

    It is really impressive to share these useful contents and moreover if U wanna looking for best home utilities try out our EG-Doors of U.K limited for comfort and safety attachments...

  • stell

    1/10/2010 11:21:24 AM |

    from this article, i can undestand what is AJAX and Actually, i don't undestand before

  • Reverse Phone Lookup

    1/13/2010 11:07:50 PM |

    I have been reading your post regularly. They are highly informative and helpful.

  • web design

    1/17/2010 11:38:11 PM |

    Thank for your article about ASP and AJAX

  • javindo

    1/20/2010 9:32:32 AM |

    I'm curious, why can't we just disable the button using simple javascript ?

  • Torront

    1/21/2010 2:21:32 PM |

    Very interesting article. Couldn't be written any better. Browsing this post reminds me of my old friend. He always kept speaking about this. I will send this post to him. Am sure he will have a good chuckle

  • Liam

    1/25/2010 7:43:41 AM |

    Interesting post Smile

  • Abogado Laborista

    1/25/2010 11:46:16 PM |

    Great Post, I love to read articles that are informative and acutally have good content. Thank you for sharing your knowledge and I look forward to reading more.


    1/27/2010 9:14:46 AM |

    good post!!!!!!!!

  • Eugene Marketing

    1/29/2010 1:02:24 PM |

    Do you spend a lot of time to moderate the comments here?

  • Statistics Help

    1/30/2010 1:37:37 AM |

    I really appreciate your professional approach. These are pieces of very useful information that will be of great use for me in future.

  • outsourcing jobs in Indonesia

    2/2/2010 2:33:54 AM |

  • outsourcing provider in Indonesia

    2/2/2010 6:01:13 AM |

    I must say, I found this to be worthwhile reading about this topic. Appreciate the information.

  • Payday Loans

    2/2/2010 8:57:19 PM |

    It’s a fastidious and instructive article. Things are ordered wellspring. Get to bonk lot’s of thing which were not region to me.

  • Ty

    2/2/2010 11:32:59 PM |

    Interesting blog because disable submit button after user click is always more complexthan it appears.

  • Registry Cleaners

    2/6/2010 3:43:04 AM |

    as I have already seen that there is commenting going on in large I indicate that how your blog popular is?

  • Boris

    2/6/2010 6:55:30 PM |

    This is a super post man! Really good post

  • Andrew

    2/10/2010 2:01:42 AM |

    Blogs are a great way to connect to people and provide useful information.  You are able to achieve that in this post. Thanks for sharing this.

  • Vasil

    2/12/2010 5:43:12 AM |

    4th part dont understend theese tag - if (Page_Validators !== 'undefined' && Page_Validators !== null) {
    142.        for (var i = 0; i < Page_Validators.length; i++) {
    143.            var validator2 = Page_Validators[i];
    144.            var controlToValidate2 = document.getElementById(validator2.controltovalidate);
    145.            if (controlToValidate2 === null) {
    146.                ValidatorEnable(validator2, false);

  • Страховка

    2/14/2010 8:03:22 AM |

    Хорошая информация, для продвинутых пользователей, Украина тоже читает это!

  • Susan

    2/14/2010 2:42:16 PM |

    I know this is really boring and you are skipping to the next comment,
    but I just wanted to throw you a big thanks - Great Post!

  • Richard

    2/14/2010 5:43:16 PM |

    your post is simple but have a informative and useful articles thanks for sharing it.

  • posizionamento nei motori di ricerca

    2/19/2010 3:40:12 PM |

    I have forwarded this blog to my friends because it's very interesting.

  • discoteche roma

    2/22/2010 11:44:19 AM |

    I have forwarded this blog to my friends because it's very interesting.

  • Steve

    2/27/2010 10:59:29 AM |

    Great post, keeping me from working

  • Yachtcharter Griechenland

    2/28/2010 9:36:03 PM |

    Wow, I never knew that Disable an ASP.NET button during PostBack with AJAX loading background image. That's pretty interesting...

  • Bradly

    3/4/2010 11:41:14 AM |

    Great article , keeping me from working

  • Alberta Business Plans

    3/12/2010 8:32:12 PM |

    i have visit this web i have book mark this it is very latest article i will visit again definately

  • Shannon McMillan

    4/24/2010 2:02:31 PM |

    Great post! I've always wondered why some submit buttons take such a long time to go through!Now I know that it is a deeper problem and not something wrong with my computer.

  • Chris Maio

    7/1/2010 11:03:34 AM |

    Appreciation for taking some time to discuss disable submit button after user click, I feel strongly about it and love learning additional on this topic. If probable, since you gain expertise, would you�d mind updating your webpage with added information? Extremely beneficial for me.

  • jason

    7/12/2010 2:27:45 PM |

    your writing is constantly getting better

  • TonnyD

    1/13/2011 11:37:30 AM |

    Thanks.Very interestin article.

  • The Colonndade Homes for sale

    2/19/2011 7:40:25 PM |

    Hey very nice weblog!!

Pingbacks and trackbacks (5)+

Add comment