简体   繁体   English

jQuery验证具有动态表单的插件

[英]jquery validate plugin with dynamic forms

How to use this code (from the demo ) if the form isn't created yet: 如果尚未创建表单,如何使用此代码(来自demo ):

jQuery("#form").validate({
  submitHandler: function(form) {
    jQuery(form).ajaxSubmit({
      target: "#result"
    });
  }
});

One way which doesn't work is to call the validation on a on('click', like this: 一种无效的方法是在on('click',调用验证on('click',如下所示:

$(document.body).on('click', '.submitBtn', function(){
   var $form =$('form'+this.id);
       $form.validate({
         submitHandler: function($form) {
           $form.ajaxSubmit({
             target: "#result"
           });
         }
       });
});

Any suggestions? 有什么建议么?

Try using jQuery("#form").validate().form() after the form is created. 创建表单后,尝试使用jQuery("#form").validate().form() http://docs.jquery.com/Plugins/Validation/Validator/form http://docs.jquery.com/Plugins/Validation/Validator/form

$(document.body).on('click', '.submitBtn', function(){
   var $form =$('#form'+this.id);
       $form.validate({
         submitHandler: function($form) {
           $($form).ajaxSubmit({  //need to properly refer to jQuery object
             target: "#result"
           });
         }
       }).form();
});

I think this answer to a similar questions could help you out a lot https://stackoverflow.com/a/4359915/351366 我认为这个类似问题的答案可以为您提供很多帮助https://stackoverflow.com/a/4359915/351366

Here's a shot at making it more specific to your code 这是使它更具体地针对您的代码的一种尝试

Create a custom event to fire once your form is on the page 创建自定义事件以在表单出现在页面上时触发

$(document).bind('bindForm', function (e) {
    jQuery("#form").validate({
        submitHandler: function(form) {
          jQuery(form).ajaxSubmit({
             target: "#result"
          });
        }
    });
});

Then when your form is loaded, trigger your custom event 然后,在加载表单时,触发您的自定义事件

$(document).trigger('bindForm'); //trigger our validate form

When you want to check to see if your form is valid in another function 当您想查看表格是否在另一个函数中有效时

$(".submitBtn").live("click",function() {
    if (!$("#form").validate().form()) {
        return;
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM