jQuery Validation with multiple (mostly) identical forms
December 22nd 2009 4:16 pm by Matt
I came across an issue today with jQuery with multiple forms. I’ve got a page that’s dynamically generating possibly several dozen mostly identical forms on a single page. “Why would you do that?” you might ask. Well, imagine a data set where I want to be able to edit each row independently and you’ve got an idea of what I’m doing. I know it’s not pretty, but it’s definitely an easy and straight forward way to do this. Here’s an example of a typical form that I might have 15 of in this script:
1 2 3 4 5 6 7 8 9 | <form action="/form/process" method="post" class="question_form"> <label for="questiont">Question:</label> <input class="required" type="text" name="question" /> <br /> <label for="answer">Answer:</label> <input class="required" type="text" name="answer" /> <br /> <input type="submit" value="Submit!" /> </form> |
So, you’d think the logical thing to do for quickly running validation on all these forms would be:
1 2 3 | $(document).ready(function() { $(".question_form").validate(); }); |
Unfortunately, because the form fields shared the same name, the validation plugin hiccuped with this solution. Now I’m using custom error classes and rules in my actual implementation, so maybe this problem is more specific and isn’t reproduced quite this easily – but basically what happens is that if you have 10 “Question” forms, the validation plugin will see the “Question” field on the first form and call it good. Obviously, we can’t have that, we want each form validating separately.
The solution? Use the each selector to iterate through the forms, of course:
1 2 3 4 5 | $(document).ready(function() { $(".question_form").each(function() { $(this).validate(); }); }); |
voila! Easy, but I want to remember it for later

This is exactly what I was looking for, didn’t notice the difference between this and $(this)