Grefcs
Grefcs

Reputation: 11

Perform jQuery only if form is valid

I'm using the jQuery validate plugin and I'm also using jQuery to make a closing animation for a popup that my form is in.

Naturally, I don't want the popup to close if the form is invalid and errors need fixed.

Here's what I'm working with...

Form validation:

$(document).ready(function(){
    $("#form").validate({
       errorContainer: "#messageBox1",
       errorLabelContainer: "#messageBox1 ul",
       wrapper: "li",
    });
    });

Submit form button action:

$("#ContinueButton").click(function(){
$("#refer-a-friend").animate({
    top: "0%",
    opacity: 0
}, 500 );
});

So how would I make it so the close animation only fires if the form is valid?

Upvotes: 1

Views: 1698

Answers (2)

kasdega
kasdega

Reputation: 18786

$("#ContinueButton").click(function(){
   if($("#form").valid()) {
      $("#refer-a-friend").animate({
         top: "0%",
         opacity: 0
       }, 500 );
   }
});

http://docs.jquery.com/Plugins/Validation/Validator

http://docs.jquery.com/Plugins/Validation/valid

Upvotes: 1

Mike G
Mike G

Reputation: 4793

Your validation will be run when #form is submitted. Your #ContinueButton needs to either be type="submit", or call $("#form").submit();

Once you have the button submit firing the validation, take a look at the submitHandler option in the documentation, it should be what you need. Something like this:

$("#form").validate({
    submitHandler: function(form) {
      //perform your animation here 
   }
});

Upvotes: 1

Related Questions