Monday, March 10, 2008

JavaScript - Disable a button after click to prevent subsequent

As a developer you may never double-click a submit button, but your website users might do so, and execute the submit button code twice. They might as well click multiple times while it’s still in progress. If you’re running database operations or sending emails on the button click handler, double-clicks may create unwanted results in your system. Even if you’re not doing anything critical, it will overload your server with unnecessary calls.
To prevent subsequent postbacks to server, as soon as the user clicks the submit button
you can disable it and change its text in the onclick event handler as follows:
JavaScript:
function DisableButton(buttonElem)

{
buttonElem.value = 'Please Wait...';
buttonElem.disabled = true;
}

ASPX:
<asp:button id="btnSubmit" runat="server" Text="Submit" />
C#:
protected void Page_Load(object sender, EventArgs e)
{
btnSubmit.Attributes.Add("onclick", "DisableButton(this);" +
Page.ClientScript.GetPostBackEventReference(this,
btnSubmit.ID.ToString()));
}

No comments: