tim peterson
tim peterson

Reputation: 24305

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?

Upvotes: 2

Views: 4397

Answers (2)

Andy E
Andy E

Reputation: 538

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

Upvotes: 0

Brian Glaz
Brian Glaz

Reputation: 15676

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

Upvotes: 8

Related Questions