jquery - 在使用 Ajax 生成的表单上使用 jquery 验证插件

标签 jquery jquery-validate

使用 jQuery 验证插件时,如何验证使用 ajax 生成的表单?

我的意思是问,当页面加载时,表单最初不会出现在页面上,而是使用ajax添加到页面上。

我正在按照 bassistance.de/jquery-plugins/jquery-plugin-validation/ 上的示例进行操作,但验证插件似乎不会验证表单。否则,它工作得很好。有没有办法做到这一点。就像 jquery 使用 live() 一样,我可以使用什么东西让插件在这种情况下工作吗?

我这样做:

$("#thisForm").validate({

    rules: {

    },

    messages: {

    },

    submitHandler: function() {
    $.ajax({
            type: "POST",
             url: "/",
            data: $('#thisForm').serialize(),
        dataType: "json",
           cache: false,

        beforeSend: function(html) {

        },

    success: function(signInData) {


        },

        });
    }
});

最佳答案

引用OP:

"... the form does not initially appear on the page when the page loads, but is added to the page using ajax. ... like jquery uses live(), is there something I can use to make the plugin work in this scenario?"

没有可用的方法将 jQuery Validate 插件委托(delegate)绑定(bind)到尚未构造的表单。

由于 .validate() 是插件的初始化方法,因此您只需在动态创建此表单后立即调用它即可。

但是,您尚未显示创建表单的代码,因此本示例假设您通过单击某项来创建表单。根据需要进行调整...只需记住,在调用 .validate() 初始化插件之前,您需要确保 ajax 已完成(新表单存在)。

$(document).ready(function() {  // ensure the DOM is ready

    $('#something').on('click', function() { // clicking something to create the form

        $.ajax({  // your ajax code to create the form
            // your ajax options,
            complete: function() { // fires after the ajax is fully complete
                $("#thisForm").validate({ // initialize the plugin on the new form
                    // options & rules
                });
            }
        });

    });

});

complete: - A function to be called when the request finishes (after success and error callbacks are executed).

查看:http://api.jquery.com/jQuery.ajax/

关于jquery - 在使用 Ajax 生成的表单上使用 jquery 验证插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18678869/

相关文章:

javascript - 使用加号按钮添加多个文本框并通过 PHP 提交

javascript - 落下的字母和方 block 之间的碰撞

jquery - 如何为所有表单设置一个invalidHandler?

jquery - 字段取决于另一个字段在调查表中的答案

javascript - 如何使用 jQuery 验证插件在元素下方显示错误消息

jQuery 复选框撤消解决方案

php - 单击链接时更改颜色

jquery - 发现 jQuery 对象确实包含一个现有节点

javascript - 如何将 ajax $.get 值传递给 jQuery 中的另一个 $.get 函数?

jQuery 验证插件在 IE 中清除文件输入值