2

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?

user229044
  • 232,980
  • 40
  • 330
  • 338
tim peterson
  • 23,653
  • 59
  • 177
  • 299

2 Answers2

8

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();
});
tim peterson
  • 23,653
  • 59
  • 177
  • 299
Brian Glaz
  • 15,468
  • 4
  • 37
  • 55
0

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;
    }
});
Community
  • 1
  • 1
Andy E
  • 508
  • 8
  • 15
  • thanks for the link and answer, Brian's suggestion seems a little more succinct so that's what i'll go with but good to know – tim peterson Jun 08 '12 at 18:00
  • No worries, I agree that is more of what you probably want, and I also learned something as well. – Andy E Jun 11 '12 at 12:29