55

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?

rick schott
  • 21,012
  • 5
  • 52
  • 81
Goutham
  • 1,051
  • 3
  • 10
  • 8

16 Answers16

47

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;
kmonty
  • 497
  • 4
  • 4
  • day 1 with asp.net, my button gets disabled but never gets enabled again, what could I be missing – Muds Jan 17 '19 at 16:39
  • It does not work. My button is still enabled and I can click on it again while it is still processing the response. – Zizzipupp Oct 25 '19 at 08:38
37

I have found this, and it works:

btnSave.Attributes.Add(
    "onclick", 
    "this.disabled = true;" + ClientScript.GetPostBackEventReference(btnSave, null) + ";");
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
gkneo
  • 501
  • 4
  • 4
  • 3
    What's clientScript ? – Bob Swager Jul 21 '17 at 11:42
  • i believe they're referring to Page.ClientScript (in System.Web.UI namespace) https://stackoverflow.com/questions/11808329/the-name-clientscript-does-not-exist-in-the-current-context – mn. Aug 14 '19 at 02:36
17

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.

Donnelle
  • 5,689
  • 3
  • 27
  • 31
  • 1
    Unfortunately, this doesn't appear to work. The button is still enabled while waiting for the post to complete (meaning you can click on it many times). – MC9000 Oct 31 '18 at 05:32
  • 1
    Excellent solution!, it's working perfectly for me thanks!!. – Josue Barrios Mar 01 '19 at 16:53
13

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!

Shaun Keon
  • 717
  • 7
  • 4
  • Worked perfectly for what I needed to accomplish. You can also add `this.style.backgroundcolor = '#abcdef';` to change style aspects of the element. – Shawn Gavett Apr 25 '17 at 20:42
  • 2
    This works perfectly. Just want to emphasize the need for `UseSubmitBehavior="false"`, without that, your button click will not fire in code-behind. – Nick Jan 04 '18 at 17:06
  • @ShawnGavett where do you exactly add that line? – Zizzipupp Oct 25 '19 at 08:44
  • 1
    @Zizzipupp - you can create a CSS class and apply it to the `CssClass` attribute on the button, or you can do an inline style with the `Style` attribute. – Shawn Gavett Oct 30 '19 at 18:14
11

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

Zoe
  • 27,060
  • 21
  • 118
  • 148
Sachin Karche
  • 121
  • 1
  • 9
10

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" />
eqiz
  • 1,521
  • 5
  • 29
  • 51
  • This is the only answer I could find that actually works! Even better, the button changes to let the user know it's being submitted (no giant DIV overlays or other nonsense!) – MC9000 Oct 31 '18 at 05:43
5
<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>
Reshma
  • 1,370
  • 7
  • 24
  • 38
3

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

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

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
Taylor Brown
  • 1,689
  • 2
  • 17
  • 33
2

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>
rick schott
  • 21,012
  • 5
  • 52
  • 81
  • And where do you put this code? If it is a standalone script, how do you call it from the c# code-behind? – Zizzipupp Oct 25 '19 at 08:33
  • Could do either, tricky part is the Id is generated so you need to pass it into a function if put in a standalone script. – rick schott Oct 30 '19 at 13:13
1

using jQuery:

$('form').submit(function(){
    $(':submit', this).click(function() {
        return false;
    });
});
mtntrailrunner
  • 761
  • 6
  • 11
1

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"

1

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" />
Matteo Conta
  • 1,423
  • 13
  • 17
0

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.

FJT
  • 1,923
  • 1
  • 15
  • 14
0
<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>
Imad
  • 7,126
  • 12
  • 55
  • 112
0

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

steinberg
  • 610
  • 4
  • 11