WhiskerBiscuit
WhiskerBiscuit

Reputation: 5157

Allow a button only to be clicked once in MVC

This question has been asked and answered several times, but I must be missing something basic. Anytime one of the submit buttons are pressed, I want it to be disabled so no "double clicks" can occur. (I've tried the jQuery "one" function as well). The click, should of course submit the form.

Upon submission of the form, the controller sleeps for several seconds to emulate processing time, then this view is served again where all the buttons should be enabled again.

I'm using VS2013 and created a new MVC app by doing:

File|New Project|Asp.Net Web Application|MVC

Views\Home\Index.vbhtml

<script>
    $('input[type="submit"]').click(function () {
        $(this).prop('disabled', true);
    });
</script>

@Using (Html.BeginForm())
    @<input type="submit" name="prevStep" value="Previous" />
    @<input type="submit" name="saveStep" value="Save" />
    @<input type="submit" name="nextStep" value="Next" />
End Using

HomeController.Vb

Public Class HomeController
    Inherits System.Web.Mvc.Controller

    Function Index() As ActionResult
        System.Threading.Thread.Sleep(1000)
        Return View()
    End Function
End Class

Upvotes: 1

Views: 2310

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038930

Try this one:

<script>
    $(function() {
        $('input[type="submit"]').click(function() {
            $(this).attr('disabled', 'disabled');
        });
    })
</script>

or if you place your script AFTER the buttons you don't need to wrap it in a document.ready:

<script>
    $('input[type="submit"]').click(function() {
        $(this).attr('disabled', 'disabled');
    });
</script>

and if you are using jQuery 1.6+ you should use the .prop() function to disable the button:

$(this).prop('disabled', true);

Upvotes: 6

Related Questions