Validating multiple forms on the same page

前端 未结 6 498
面向向阳花
面向向阳花 2021-01-14 03:03

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

6条回答
  •  心在旅途
    2021-01-14 03:19

    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  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 elements on the page, you can target them all with $('form') as done in the demo above.

提交回复
热议问题