在使用Ajax生成的表单上使用jqueryvalidation插件

使用jQueryvalidation插件时,如何validation使用ajax生成的表单?

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

我正在关注bassistance.de/jquery-plugins/jquery-plugin-validation/上的示例,但似乎validation插件不会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:

“…页面在页面加载时最初没有显示在页面上,但是使用ajax添加到页面中….就像jquery使用live() ,有什么我可以用来使插件在这里工作情景?”

没有方法可以将jQuery Validate插件委托绑定到尚未构造的表单。

由于.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: – 请求完成时要调用的函数(执行成功和错误回调之后 )。

请参阅 : http : //api.jquery.com/jQuery.ajax/

尝试使用.on()添加DOM委派

 $("body").on("validate", "#thisForm", function() { }); 

编辑以解决以下评论:

如果无法通过父元素委派事件,则必须在将事件处理程序放入DOM后绑定它。 以下是使用jQuery的示例:

 $("addmyHTMLhere").html('
').find('form').validate({put your validate stuff here});

遇到同样的问题,不确定是否有更好的方法来做你想做的事,但这就是我提出的:

 $(document.body).on('submit', '#myform', function(e){ // Set your validation settings and initialize the validate plugin on the form. $(this).validate({ submitHandler: function(form) { // do your ajax submit or whatever you want. } }); // submit the form pro grammatically. $(this).submit(); }); 

再说也许有更好的方法可以做到这一点,但这就是我认为到目前为止工作得很好的方法。

我在通过AJAX加载表单时也遇到了这个问题,并且还希望使用AJAX提交表单(以保持当前页面…)。 这对我有用:

 //Newbie note: ajaxFormCallback is the callback function - which runs once my AJAX loaded form has been added to the page. var ajaxFormCallback = function(){ var form = $('#form-id-here'); form.validate({ rules: { 'name': { required: true }, 'email': { required: true, email: true } }, messages: { 'name': { required: 'Name is required' }, 'email': { required: 'Email address is required', email: 'Invalid email address' } }, submitHandler: function(form){ //submit form via AJAX $.ajax({ type: 'POST', url: '/path/to/submit/form/?' + $(form).serialize() + '&ajax=1', success: function(data){ //replace my form with a response: $(form).parents('.response').replaceWith(data); } }); } }); };