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?

codegy
  • 2,089
  • 4
  • 24
  • 24

2 Answers2

3

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.

LeftyX
  • 34,522
  • 20
  • 128
  • 188
Nick Craver
  • 594,859
  • 130
  • 1,270
  • 1,139
  • I've tried that. But the real problem is dealing with dynamic form elements. That's why I used Jquery's live(). – codegy Feb 08 '10 at 04:52
3

Somehow this seems to work:

$('.dynamicForm').live('mouseover',function(){
    $(this).validate({
        submitHandler:function(form){
            if(confirm("Are you sure?")){
                form.submit();
            }
        }
    });
});
codegy
  • 2,089
  • 4
  • 24
  • 24
  • jQuery .live() has been removed in version 1.9 onwards. Refer to this post https://stackoverflow.com/questions/14354040/jquery-1-9-live-is-not-a-function – Hamza Ali Dec 31 '19 at 05:37