javascriptjquerybootstrapvalidator-1000hz

Load jQuery Plugin on dynamic created form


To validate a form, I use a validation plugin. Example:

$ ( '# post-form').validator()

I would like to load the plugin on a form that is dynamically created via an Ajax return. What I try:

$ (document).on ('ready', '# post-command-detail').validator ();

But it does not work. How can I activate the validator on a form created 100% dynamically?

To know: # post-command-detail is the id of the concerned form.


Solution

  • You can initialize the plugin inside the ajax callback, right after the new form creation:

    $.ajax({
        ...
        success: (data: any): void => {
            if (data) {
                // Append new form
                $('body').append($('<form id="post-command-detail" />'));
    
                // Select the new form and init the plugin
                $('#post-command-detail').validator();
            }
        }
    });