Introduction
Many times, a developer wants the clicking of one button on the screen to disable the other buttons on the screen to prevent multiple submissions. Attached is some JavaScript that provides this feature.
Using the Code
Over the internet, there are several ways to prevent multiple button clicks in ASP.NET, this is just another way to do it. Click here in order to see a server side control doing a similar thing that this JavaScript is doing.
<script language="JavaScript">
<!--
function DisableButtonClick(valGroup) {
var cont = false;
if (typeof Page_ClientValidate != "undefined") {
cont = Page_ClientValidate(valGroup);
}
else {
cont = true;
}
if (cont) {
var btn = document.getElementById('<%= BtnSaveGeneral.ClientID %>');
if (btn != null) {
btn.disabled = true;
btn.value = 'Saving...';
}
}
}
-->
</script>
Usage of this would be inline in HTML.
<asp:Button ID="BtnSave" runat="server" Text="Save" OnClick="BtnSaveGeneral_Click"
OnClientClick="DisableButtonClick('Save');"
UseSubmitBehavior="false" ValidationGroup="Save" />
Or in the code behind by changing the "onclientclick
" attribute to the button.
BtnSave.Attributes.Add("onclientclick", "DisableButtonClick('Save');
BtnSave.UseSubmitBehavior = false;
Set the UseSubmitBehavior
to false
so ASP.NET will render JavaScript to allow the Button_Click
event to fire on the server even though the JavaScript disables the button.
You can send in a blank ValidationGroup
too if you want, by sending in an empty string
.
Points of Interest
This JavaScript function explicitly names the buttons to clear inside the function. Other options would be to pass into the function the buttons to disable when you call the OnClientClick
, or to register each button that you wish to disable into an array and iterate through the array of names, disabling each control found.
History
- 25th June, 2009: Initial post