Search code examples
javascriptjqueryjquery-validatejquery-forms-plugin

Initialize jQuery validate() function on multiple dynamically added forms


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 only allow submit if input is changed

I'm wondering how to do this for multiple dynamically added forms without wrapping the $('#form').validate({}) function inside of a on('click', 'input[type="submit"]', function.

Take this code for example:

var id="some identifier for the specific form that is submitted";
`$('#form'+id).validate({})`
  1. How does this unique identifier, id, which is required to distinguish each form get created in the first place?
  2. And what if you don't know the id after the page is loaded because it has been created dynamically, e.g., by AJAX.

I have been doing this but this is is what's not recommended:

$(document.body).on('click', 'input[type="submit"]', function(){
  var id=this.id;
  $('#form'+id).validate({});
});

thoughts?

thanks, tim


Solution

  • 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();
        });
    });