SolutionCottage.com
Posted  20 Nov 2008 - 23:20:26

Category: ASP.net


Prevent double click on Ajax button.

Issue:
I have an Ajax enabled mail form where the user can send me comments. The idea is that the user should just click this button once, not more. Since this is a client function, you can not use the codebehind to disable the button since this is too late in the chain of events.
I had a solution at first that added an onclick event to the button via JavaScript, and that worked. The problem was that I need to send the mail in the codebehind and with yet another event trigger, the mail got sent twice.

Solution:
The trick is to not bind the button twice but still disable the button. We can use the request itself for this like this:

<script type="text/javascript">

var requestMgr = Sys.WebForms.PageRequestManager.getInstance();

requestMgr.add_initializeRequest(InitializeRequest);
requestMgr.add_endRequest(EndRequest);

function InitializeRequest(sender, args)
{


$get(args._postBackElement.id).disabled = true;
$get(args._postBackElement.id).value = "Sending...";
}

function EndRequest(sender, args)
{


$get(sender._postBackSettings.sourceElement.id).disabled = false;
}

</script>

This simply creates an instance of a PageRequestManager and sets event listeners to the request itself. This is also good for my Ajax validators on the form, since this won't happen until the request actually executes, which is after the page is valid. In clear text, the button will not be disabled until the page is valid. Then I use jquery (www.jquery.com) to fetch the buttons, which is the sender in this case. Simple enough and just sends one email.



Marked as helpful by 21 users




1 comment:

10/26/2009 11:33:34 AM  Nasir  wrote:

Great Job it is working on IE and firefox also. Thanx









© SolutionCottage 2008-2011 9/26/2017 10:17:53 AM