在动态创建的表单上加载 jQuery 插件

Load jQuery Plugin on dynamic created form

为了验证表单,我使用了验证插件。 示例:

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

我想在通过 Ajax return 动态创建的表单上加载插件。我的尝试:

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

但是不行。 如何在 100% 动态创建的表单上激活验证器?

要知道:#post-command-detail是相关表单的id。

您可以在 ajax 回调中初始化插件,就在新表单创建之后:

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

您可以这样做,只需在将 html 渲染到元素后调用验证即可:

$(document).ready(function () {
   
    validateForm("#form");
    //once your ajax succeeded you can do something like this
    $('#dynamicForm').html('<form id="form1" method="post" action="#"> <label for="name">Name</label> <input type="text" name="name" id="name" /><button type="submit">Submit</button> </form>');
    validateForm("#form1");

});

function validateForm(form){
$(form).validate({
        rules: {
            "name": {
                required: true,
                minlength: 5
            },
           
        },
        messages: {
            "name": {
                required: "Please, enter a name"
            },
            
        },
        submitHandler: function (form) { // for demo
            alert('valid form submitted'); // for demo
            return false; // for demo
        }
    });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/additional-methods.js"></script>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet"/>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>

<form id="form" method="post" action="#">
    <label for="name">Name</label>
    <input type="text" name="name" id="name" />
   
    <button type="submit">Submit</button>
</form>


<div id="dynamicForm" >

</div>