Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC: Disable Submit button if Client Validation passes

I have a simple MVC4 form with Client Validation enabled:

 @{ Html.EnableClientValidation(); }
 @{ Html.EnableUnobtrusiveJavaScript(); }
 @using (Html.BeginForm("Search", "Search", FormMethod.Post, new { id = "frmMain" }))
    {
      @Html.AntiForgeryToken() .....
      <input type="submit" value="Search" id="btnSubmit" />

When the user clicks the submit and all validation passes on the client, I wish to have the submit button disabled as per jQuery below. How do I know if the validation has passed client side in side my jQuery script?

<script type="text/javascript">

$(document).ready(function () {
    $('input[type=submit]').click(function (e) {
        $(this).attr('disabled', true);
        $(this).attr('value', 'Working');
        $('#frmMain').submit();
    });
});

like image 920
Ian Vink Avatar asked Dec 14 '12 17:12

Ian Vink


2 Answers

You can hook this code into the form validator. Just make sure it executes AFTER the jquery.validator.unobtrusive.

<script>
    $("#you-form-id").data("validator").settings.submitHandler = function(form) {
         $("#submit-button").attr("disabled",true).val("Working");
         form.submit();
    };
</script>
like image 86
Felipe Leusin Avatar answered Oct 15 '22 15:10

Felipe Leusin


I had some issues when return a partail from the controller action. Instead I hooked in to the submit function and checked that the form was valid like this:

        $('form').submit(function () {
            if ($(this).valid()) {
                $('#order-form-submit-button').attr("disabled", true).val("wait...");
            }
        });
like image 13
David Avatar answered Oct 15 '22 17:10

David