开发者

How to create a universal jquery validate and reset function call

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..


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.


try this maybe?

$("form").each(function () { 
var validator = $(this);
validator.validate(); 
validator.resetForm(); 
$("#reset").click(function () { 
    validator.resetForm(); 
}); 
 });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜