How to create a universal jquery validate and reset function call

白昼怎懂夜的黑 提交于 2019-12-11 07:27:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!