views:

514

answers:

2

I'm using the Jquery Validation Plugin to forms loaded via Ajax (dynamic forms). I know that as of Jquery 1.4, live events on submit is now possible. Now the problem is I want to show a confirm message after the dynamic form has been validated. My code looks like this:

$('.dynamicForm').live('submit',function(){
   $(this).validate();
   if($(this).valid()){
      if(!confirm('Are you sure?'))
         e.preventDefault();
   }
});

It's not working as expected. Somehow confirmation shows first, then at the second time I submit the form, that's the time the validation happens. Any ideas?

+1  A: 

Use the submitHandler function available in the validate options:

$(". dynamicForm").validate({
   submitHandler: function(form) { //Only runs when valid
     if(confirm('Are you sure?'))
       form.submit();
   }
})

From the docs - submitHandler:

Callback for handling the actual submit when the form is valid. Gets the form as the only argument. Replaces the default submit. The right place to submit a form via Ajax after it validated.

Nick Craver
I've tried that. But the real problem is dealing with dynamic form elements. That's why I used Jquery's live().
Gian Basagre
A: 

Somehow this seems to work:

$('.dynamicForm').live('mouseover',function(){
    $(this).validate({
        submitHandler:function(form){
            if(confirm("Are you sure?")){
                form.submit();
            }
        }
    });
});
Gian Basagre