Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating multiple forms on the same page

For example I have 3 forms in a page with the same names. How can I validate all these forms with one validate method?

<form id="formID">
<input name="nick">
<input type="submit">
</form>

<form id="formID">
<input name="nick">
<input type="submit">
</form>

<form id="formID">
<input name="nick">
<input type="submit">
</form>

I want to validate only the submitted form not all at the same time.

$('#formID').validate({
})

My solution does not work. I also find I can't add different IDs because these forms are in a PHP loop and it must have same ID.

like image 297
Wizard Avatar asked May 29 '14 19:05

Wizard


1 Answers

When you need to apply the same .validate() method to multiple forms, you simply need a jQuery .each() and you can target them all at once by the form tag.

$('form').each(function() {   // <- selects every <form> on page
    $(this).validate({        // <- initialize validate() on each form
        // your options       // <- set your options inside
    });
});

DEMO: http://jsfiddle.net/K6Tkn/


Quote OP:

"I also find I can't add different IDs because these forms are in a PHP loop and it must have same ID."

Then your PHP loop is not constructed properly. Every id on a page must be unique or the HTML markup is invalid. You can simply use class instead of id. Otherwise, if there are no other <form> elements on the page, you can target them all with $('form') as done in the demo above.

like image 120
Sparky Avatar answered Oct 21 '22 23:10

Sparky