问题
I am using jQuery Validation Plugin 1.9.0 with jQuery 1.7.2.
I want my form to be validated with jquery validation plugin. It works fine in Firefox 20.0.1 and IE 10. But in Chrome (26.0.1410.64 m) and in Opera (12.14) I cannot click on cancel in my form without preventing validation to be done.
This is my javascript code:
 submitHandler: function(form) {
  if (this.submitButton.value != 'cancel') {
   $(form).hide();
   $('#load').show();
   $(form).submit();
  }
  else {
  event.preventDefault();
  }
 }
When I click on cancel on FF and IE I go back to my web home page as expected, but when I do this in Chrome and Opera my error messages are displayed as the form is incompletely filled. In both case the event.preventDefault() is called but it seems the behavior is different depending on the navigator.
Do you have any idea of what may be wrong ?
Thanks for your help !
回答1:
You are misunderstanding the purpose of .preventDefault().  It's not meant for preventing the default behavior of a function.  It's meant for canceling the built-in behaviors of regular elements, i.e., remove the navigation and history from an anchor tag, etc.
See: http://api.jquery.com/event.preventDefault/
AFAIK, you cannot programatically turn validation on and off.  Once you initialize the plugin with .validate(), there is no method to "un"-initialize it.
However, to simply use a "cancel" button, there are several methods...  one is to make sure you keep the cancel button outside of the <form></form> and then use a click handler to do something else with it.
DEMO: http://jsfiddle.net/TZVA6/1
Or another method, as pointed out by Rocket Hazmat, is to give the button a type="button" attribute which prevents the default submit action.
DEMO: http://jsfiddle.net/TZVA6/2/
来源:https://stackoverflow.com/questions/18389046/event-preventdefault-does-not-work-in-chrome-and-opera