8

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();
    });
});

2 Answers 2

14

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Is this safer than simple wrapping the function in something like: if ($('#frmMain').valid()) {
I supposed both ways work, and there's no right answer when you're using jQuery Validator plugin. With the submitHandler (despite the code being uglier) you're only processing the validation once and I'm not entirelly sure if calling valid() would re-validate all the fields, something that can have some marginal performance impact.
13

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...");
            }
        });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.