Thursday, January 7, 2010

Disable button in onclick and process the button click event

This is what I need to implement for one of my project. I am using Ajax and if user tries to hit the submit the button more than once, only the very first request should submit to server and all other requests shouldn't make any request. So, for this I need to disable the button when first  time click on button and enable it after processed. But, I faced a problem that when I try to disable the button in javascript of client side click event then the postback event not raising at all. There are couple of ways we can implement this. First, I tried from server side code.

Solution 1:

btnSubmit.Attributes.Add("onclick","javascript:" + btnSubmit.ClientID + ".disabled=true;" + this.GetPostBackEventReference(btnSubmit));
But, this solution won't work in all scenarios and especially if there are validations.

Solution 2:

OnClientClick='javascript:this.disabled=Page_ClientValidate("");' UseSubmitBehavior="false"
For ASP Button the two properties onclientclick and usesubmitbehavior will do magic for us. In onclientclick event I am disabling the button if and only if the validation passed. Go back to my previous post. It describes how to validate the controls in client side and give the result true or false. And because of using the UseSubmitBehavior property it will automatically re-enable the button once the request processed.

Hope this gives you the enough idea. Like to know what you think. 

2 comments:

  1. Thanks for solution 2, works great in IE and Firefox, but doesn't seem to work in Google Chrome...

    Any ideas?

    ReplyDelete
  2. Hi there

    thanx a million!
    solution 2 did wonders for me!

    Jason

    ReplyDelete