Mustapha Aoussar
Mustapha Aoussar

Reputation: 5923

Form validation: if there is errors don't animate the accordion

I am using the jQuery Validation plugin on the awsAccordion. I want to open the next tab of my accordion after the validation is run without errors.

This is what i did: http://jsfiddle.net/vqL4p/7/

$('#myform').validate({ // initialize the plugin
    rules: {
        field1: {
            required: true,
            email: true
        },
        field2: {
            required: true,
            minlength: 5
        }
    },
    invalidHandler: function(form, validator){ //if there is error
        var errors = validator.numberOfInvalids();
        var message = (errors == 1) ? "One of your groups won't validate." : "Neither of your groups will validate.";
        alert(message);
        $('dt').unbind('click'); //if there is error remove click on the tab
    },
    submitHandler: function (form) { 
        alert('valid form submitted'); 
        return false;
        }
});

$('dt').click(
    function(e){
    $("#myform").valid();
});

The problem is that the unbind click $('dt').unbind('click'); works only after tab is closed and the next is opened. Do you know a way to solve this problem?
Thank you so much!

Upvotes: 0

Views: 275

Answers (1)

PSL
PSL

Reputation: 123739

You dont have to unbind the click event, instead you just need to stop the propagation and prevent rest of the handlers from being executed using event.stopImmediatePropagation(). And check for the validity of the form inside the click event using !$("#myform").valid().

Try:

     $('dt').click(function(e){
       if(!$("#myform").valid()){ //Check if form is valid or not
           e.stopImmediatePropagation(); //stop rest of the handlers from being executed
       };
     });


     $('#myform').validate({ // initialize the plugin
        rules: {
            field1: {
                required: true,
                email: true
            },
            field2: {
                required: true,
                minlength: 5
            }
        },
        invalidHandler: function(form, validator){
            var errors = validator.numberOfInvalids();
            var message = (errors == 1) ? "Validated." : "Error! the field is required";
        },

        submitHandler: function (form) { 
            alert('valid form submitted'); 
        }
    });


    $("#accordion1").awsAccordion({
            type:"horizontal",
            cssAttrsHor:{
                ulWidth:"responsive",
                liWidth:50,
                liHeight:300
            },
            startSlide:1,
            openOnebyOne:true,
            classTab:"active",
            slideOn:"click",
            autoPlay:false,
            autoPlaySpeed:500
    });

Demo

Upvotes: 1

Related Questions