rikket
rikket

Reputation: 2407

Prevent user from double clicking in ASP.NET

I have tried the following two scripts to prevent user from submitting the below form more than one. The submit button is being disabled in both cases, however the form is not being sent (placed a break point and the OnClick method is not being called)

Button:

<asp:Button ID="BtnSubmit" runat="server" Text="Submit" onclick="BtnSubmit_Click" />

Scripts:

<script type="text/javascript">        $("#BtnSubmit").click(function () {
        var button = $(this);
        button.prop('disabled', true);
        setTimeout(function () {
            button.prop('disabled', false);
        }, 5000);
    });</script>

and

$('form').on('submit', function (e) {
$('[type="submit"]').prop('disabled','disabled');
});

Upvotes: 0

Views: 858

Answers (2)

Ian
Ian

Reputation: 50933

One quick idea is to change the type of the button to "button" (instead of "submit"), instead of disabling it. That way, it won't submit the form if clicked again at least.

Another other idea comes from here: http://encosia.com/disable-a-button-control-during-postback/ -

The important text from the link:

The one pitfall that comes with disabling a submit button on the client side is that it will cancel the browser’s submit, and thus the postback. Setting the UseSubmitBehavior property to false tells .NET to inject the necessary client script to fire the postback anyway, instead of relying on the browser’s form submission behavior.

Following that, your button would look something like this:

<asp:Button runat="server" ID="BtnSubmit" Text="Submit"
  OnClientClick="this.disabled = true; this.value = 'Submitting...';" 
  UseSubmitBehavior="false" 
  OnClick="BtnSubmit_Click" />

I don't like the inline OnClientClick, so you should try taking it out and keeping your jQuery click handler, as well as setting the UseSubmitBehavior appropriately. I have a feeling the order of events shouldn't matter.

Upvotes: 3

Brian Mains
Brian Mains

Reputation: 50728

For the former, you would have to do instead:

<script type="text/javascript">        
$("#<%= BtnSubmit.ClientID %>").click(function () {
        var button = $(this);
        button.prop('disabled', true);
        setTimeout(function () {
            button.prop('disabled', false);
        }, 5000);
    });</script>

The actual ID is going to be way longer than btnsubmit, unless you have ClientIDMode="Static" defined. (something like ct100_contentplaceholder_btnsubmit). Using the ClientID property from the server locates the proper ID of the control.

Upvotes: -1

Related Questions