[javascript] Disable asp.net button after click to prevent double clicking

I have an ASP.NET button that I need to disable after the user clicks it to prevent double-clicking. Once the submit completes it has to be enabled again. Can anyone help me with this?

This question is related to javascript jquery asp.net asp.net-ajax

The answer is


<script type = "text/javascript">
function DisableButtons() {
    var inputs = document.getElementsByTagName("INPUT");
    for (var i in inputs) {
        if (inputs[i].type == "button" || inputs[i].type == "submit") {
            inputs[i].disabled = true;
        }
    }
}
window.onbeforeunload = DisableButtons;
</script>

Check this link, the most simplest way and it does not disable the validations.

http://aspsnippets.com/Articles/Disable-Button-before-Page-PostBack-in-ASP.Net.aspx

If you have e.g.

  <form id="form1" runat="server">
      <asp:Button ID="Button1" runat="server" Text="Button1" OnClick="Button1_Clicked" />
  </form>

Then you can use

  <script type = "text/javascript">
  function DisableButton() {
      document.getElementById("<%=Button1.ClientID %>").disabled = true;
  }
  window.onbeforeunload = DisableButton;
  </script>

To disable the button if and after validation has succeeded, just as the page is doing a server postback.


This works with a regular html button.

    <input id="Button1"
    onclick="this.disabled='true';" type="button"
    value="Submit" name="Button1"
    runat="server" onserverclick="Button1_Click">

The button is disabled until the postback is finished, preventing double clicking.


Try this, it worked for me

<asp:Button ID="button" runat="server" CssClass="normalButton" 
Text="Button"  OnClick="Button_Click" ClientIDMode="Static" 
OnClientClick="this.disabled = true; setTimeout('enableButton()', 1500);" 
UseSubmitBehavior="False"/>  

Then

<script type="text/javascript">
function enableButton() {
document.getElementById('button').disabled = false;
}
</script>

You can adjust the delay time in "setTimeout"


<asp:Button ID="btnSend" runat="server" Text="Submit"  OnClick="Button_Click"/>

        <script type = "text/javascript">
            function DisableButton()
            {
                document.getElementById("<%=btnSend.ClientID %>").disabled = true;
            }
            window.onbeforeunload = DisableButton;
        </script>

If you want to prevent double clicking due to a slow responding server side code then this works fine:

<asp:Button ... OnClientClick="this.disabled=true;" UseSubmitBehavior="false" />

Try putting a Threading.Thread.Sleep(5000) on the _Click() event on the server and you will see the button is disabled for the time that the server is processing the click event.

No need for server side code to re-enable the button either!


You can use the client-side onclick event to do that:

yourButton.Attributes.Add("onclick", "this.disabled=true;");

This solution works if you are using asp.net validators:

<script language="javascript" type="text/javascript">
function disableButton(sender,group)
{
    Page_ClientValidate(group);
    if (Page_IsValid)
    {
        sender.disabled = "disabled";
        __doPostBack(sender.name, '');
    }
}</script>

and change the button:

<asp:Button runat="server" ID="btnSendMessage" Text="Send" OnClick="btnSendMessage_OnClick" OnClientClick="disableButton(this,'theValidationGroup')" CausesValidation="true" ValidationGroup="theValidationGroup" />

I have found this, and it works:

btnSave.Attributes.Add(
    "onclick", 
    "this.disabled = true;" + ClientScript.GetPostBackEventReference(btnSave, null) + ";");

If anyone cares I found this post initially, but I use ASP.NET's build in Validation on the page. The solutions work, but disable the button even if its been validated. You can use this following code in order to make it so it only disables the button if it passes page validation.

<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Submit" OnClientClick=" if ( Page_ClientValidate() ) { this.value='Submitting..'; this.disabled=true; }" UseSubmitBehavior="false" />

Here is a solution that works for the asp.net button object. On the front end, add these attributes to your asp:Button definition:

<asp:Button ... OnClientClick="this.disabled=true;" UseSubmitBehavior="false" />

In the back end, in the click event handler method call, add this code to the end (preferably in a finally block)

myButton.Enabled = true;

Disable the button on the OnClick event, then re-enable on the AJAX callback event handler. Here is how I do it with jQuery.

<script>
$(document).ready(function() {

    $('#buttonId').click(function() {
         $(this).attr('disabled', 'disabled');
         callAjax();
    });

});

function callAjax()
{
    $.ajax({
      url: 'ajax/test.html',
      success: function(data) {
         //enable button
         $('#buttonId').removeAttr('disabled');

      }
    });
}
</script>

Just need to add 2 attributes for asp button :

OnClientClick="this.disabled='true';"  UseSubmitBehavior="false"

e.g.

<asp:Button ID="Button1" runat="server" Text="TEST" OnClientClick="this.disabled='true';"  UseSubmitBehavior="false" CssClass="button-content btnwidth" OnClick="ServerSideMethod_Click"  />

For more details:

https://bytes.com/topic/asp-net/answers/918280-disable-button-click-prevent-multiple-postbacks


You can do this with javascript. in your form tag, onsubmit="javascript:this.getElementById("submitButton").disabled='true';"


I like to disable the button and call a postback, this way the code behind still gets run after the button is disabled.

this is how i attach from code behind:

btnProcess.Attributes.Add("onclick", " this.disabled = true; __doPostBack('btnProcess', ''); return false;")

Then re-enable the button in code behind:

btnProcess.Enabled = True

using jQuery:

$('form').submit(function(){
    $(':submit', this).click(function() {
        return false;
    });
});

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to asp.net-ajax

How to pass multiple parameters from ajax to mvc controller? window.open with target "_blank" in Chrome Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method Disable asp.net button after click to prevent double clicking How can I convince IE to simply display application/json rather than offer to download it? How to send a model in jQuery $.ajax() post request to MVC controller method How to post ASP.NET MVC Ajax form using JavaScript rather than submit button How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET? jQuery $(document).ready and UpdatePanels? ASP.NET MVC controller actions that return JSON or partial html