jquery validate doesn't work with multiple forms

后端 未结 2 1825
有刺的猬
有刺的猬 2020-12-04 04:05

I have multiple forms in my web, you can show/hide them depeding on your query, but the jquery validate just work on the first one (Particular). Here I have my forms: https:

相关标签:
2条回答
  • 2020-12-04 04:26

    You should use unique name attribute for each input field. Because the names here is not unique, it works only for first form.

    0 讨论(0)
  • 2020-12-04 04:35

    You are attaching .validate() to the element with id="form"

    $('#form').validate({...
    
    • However, you have two form elements with this same id. You cannot use the same id more than once on a page. Repeating the id is invalid HTML. jQuery will only target the first instance.

    • Even if you used a class instead, the various jQuery Validate methods cannot be attached to selectors that target more than one element at a time. So again, even if your target correctly selected a group of elements, only the first instance would be used.


    1) You need to fix the invalid HTML by using a unique id on each form.

    <form id="form_1" ...
    
    <form id="form_2" ...
    

    2) You need to construct a selector that targets all elements in this group. You can use a "starts with" selector to grab every id that "starts with" form_.

    $('[id^="form_"]')
    

    3) You need to enclose your .validate() within a jQuery .each() so that you can apply it to each instance and not just the first.

    jQuery(document).ready(function($){
    
        $('[id^="form_"]').each(function() { // selects all forms with id starting with "form_"
            $(this).validate({ ....          // call 'validate()' method on each one
    

    Alternatively, your .form class would work here too.

    jQuery(document).ready(function($){
    
        $('.form').each(function() {  // selects all forms with class="form"
            $(this).validate({ ....   // call 'validate()' method on each one
    
    0 讨论(0)
提交回复
热议问题