Suppose you have a form with some ASP.NET validation controls on it, and you want to prevent users from clicking the form's submit button more than once.
It might sound easy at first. Just add some javascript to the asp:Button's OnClientClick to hide the button and show your custom message:
<script language="javascript" type="text/javascript">
function DisableButton(button)
{
button.style.display = 'none';
document.getElementById('loading').style.display = 'inline';
}
</script>
<asp:Button ID="LoginButton" runat="server" Text="Login" OnClientClick="DisableButton(this)" />
<span id="loading" style="display: none;">Logging in...</span>
Except if you do that, and you're using ASP.NET validation controls on the page, your user could end up in a situation like this:
Now your user is stuck because the Login button is gone!
So, this is how to get around that:
<script language="javascript" type="text/javascript">
function DisableButton(button)
{
Page_ClientValidate();
if (Page_IsValid)
{
button.style.display = 'none';
document.getElementById('loading').style.display = 'inline';
}
}
</script>
In the script above, you'll notice I'm using a Page_ClientValidate() method and a Page_IsValid boolean variable. Those are exposed as part of ASP.NET's Client-Side Validation API.
What's happening:
- Page_ClientValidate() forces the validation to happen immediately.
- If the validation tests pass (Page_IsValid), hide the button, show the message, and submit the page.
- If the validation tests fail, ASP.NET will handle showing the validation errors for you, and the page will not be submitted.
For more information on ASP.NET Validation, see this article on MSDN:
http://msdn2.microsoft.com/en-us/library/aa479045.aspx