Initialize jQuery validate() function on multiple dynamically added forms

后端 未结 1 627
清酒与你
清酒与你 2021-01-26 07:30

It is has been suggested that it is best to initialize a $(\'#form\').validate({}) function on page load rather than on a click event: jquery.form/validate plugin o

1条回答
  •  孤街浪徒
    2021-01-26 07:49

    If the form does not exist at all when the page loads, then instead of initializing the .validate() on submit, I'd initialize it immediately after the form is created...

    // code that dynamically creates #myNewform, then initialize validate()
    
    $('#myNewform').validate();
    

    (validate() should not be inside a submit handler because the validation is not initialized until after the submit button is clicked. This leads to issues when the form fails validation and must be submitted a second time. The second submit then re-initializes the plugin on the form a second time. See here, here, and here for similar issues.)

    For existing form on page...

    $(document).ready(function(){
        $('#myform').validate();
    });
    

    or for multiple form's sharing same validation options...

    $(document).ready(function(){
        ('.myform').each(function(){
            $(this).validate();
        });
    });
    

    0 讨论(0)
提交回复
热议问题