简体   繁体   中英

jquery validate plugin with dynamic forms

How to use this code (from the demo ) if the form isn't created yet:

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:

$(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. 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

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;
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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