问题
I am using the jquery validate plugin to create a validation method for all forms in an application. Using the jquery each() function to cycle each form and applyt the method. I want to achieve the reset using the same each method. how can i accomplish this?
This is the code that works:
$("form").each(function () {
$(this).validate();
});
This is the code that doesn't
$("form").each(function () {
validator = $(this).validate();
validator.resetForm();
$("#reset").click(function () {
validator.resetForm();
});
});
Please advise..
回答1:
Without the var
keyword, you're setting validator
as a global variable, and changing what it's set to with each loop (so it'll be set the to the validator of the last form at the end), just add var
when declaring it, like this:
$("form").each(function () {
var validator = $(this).validate(); //add var here
validator.resetForm();
$("#reset").click(function () {
validator.resetForm();
});
});
This will correct it so you'll reset each <form>
once, rater than the last <form>
n
times.
回答2:
try this maybe?
$("form").each(function () {
var validator = $(this);
validator.validate();
validator.resetForm();
$("#reset").click(function () {
validator.resetForm();
});
});
来源:https://stackoverflow.com/questions/4311317/how-to-create-a-universal-jquery-validate-and-reset-function-call