Thursday, February 10, 2011

ASP.NET MVC: Disable submit button after click when using Microsoft MVC client validation library.

If you want to disable submit button after it has been clicked you can use this jQuery code:

$("form").bind("submit", function (e) {
   // On submit disable form submit button
   $('input[type=submit]', this).attr('disabled', 'disabled');
});

But if you use MVC client validation

<% Html.EnableClientValidation(); %>

and the form has validation errors, the submit button will be disabled anyway.

So, we need to modify our submit form handler function to check if the form has errors.

$("form").bind("submit", function (e) {
   var mvcValidationContext = e.srcElement['__MVC_FormValidation'];
   if (mvcValidationContext) {
      var formValidationErrorsCount = mvcValidationContext.validate('submit').length;
      if (formValidationErrorsCount == 0) {
         // On submit disable form submit button
         $('input[type=submit]', this).attr('disabled', 'disabled');
      }
   }
});

Thats all.

1 comment: