问题
I have a form that is using jQuery Validate plugin for client side validation, and submits via AJAX. After the form is submitted, I would like it to reset itself. I have used the .resetForm()
method to reset the fields, which works, but the problem is that the validate plugin still immediately tries to validate fields when they're focused, and gives an error before giving the new submission a chance to enter their input.
Example Flow:
- Trigger validation initially
- Fix Validation, submit form via AJAX
- Call .resetForm(), fields are successfully cleared out
- Attempt to fill out form again
- Focus on a field (which in my case has email validation)
- Before giving you a chance to enter input, it validates and says it is incorrect.
Typically the plugin will let your enter your input before telling you that it's incorrect. Is there any way to truely reset the form and not have the validation occur on focus again, without turning off on focus validation all together?
Thanks, and here's a cleaned up/simplified code samples!
// Validation
$('#registerForm').validate({
submitHandler: function(form) {
$(form).ajaxSubmit({
success: function(response) {
if( response == 'success' ) {
resetMyForm();
}
else {
alert('unsuccessful');
}
}
})
}
});
})
function resetMyForm() {
$('#registerForm').resetForm();
v.prepareForm(); // Tried adding this, no help
v.hideErrors(); // Tried adding this, no help
}
回答1:
You need to reset the form and run the Validation plugin method resetForm
like this:
var v = $("form").validate({
submitHandler: function(form) {
//resetForm is a method on the validation object, not the form
v.resetForm();
form.reset();
}
});
That seemed to take care of any issues I saw while following your workflow. See this: http://jsfiddle.net/nxXNz/27/
回答2:
try this focusout()
function resetMyForm() {
$('#registerForm').resetForm();
v.prepareForm(); // Tried adding this, no help
v.hideErrors(); // Tried adding this, no help
$("ElementName").focusout(); // focus out which ever element you want
}
来源:https://stackoverflow.com/questions/8981064/jquery-validate-resetform-doesnt-reset-the-onfocus-validation