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