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

Answers:

Answer

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.

Answer

try this maybe?

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.