Search code examples
jqueryjquery-validatejquery-tabs

jQuery validate in tabs only works on first submit


I am trying to solve the issue where I have required form fields hidden behind tabs.

I have managed to get this half working so that when you click the submit button any required+hidden fields, it will auto display this tab.

But the problem is when you: 1. Load the page, click submit and this works fine. 2. Go back to the first tab and click the submit again and nothing happens.

http://jsfiddle.net/3xEch/

// Form validator
var theForms = $("form[method=post]:not(.noValidate)");
if (theForms.length){
    theForms.each(function(){
        var $dis = $(this);

        if($dis.hasClass("validateHidden")){
            jQuery.validator.setDefaults({
                ignore: ''
            });
        }

        validater = $dis.validate({
            errorPlacement: function(error, element) {
                var trigger = element.next('.ui-datepicker-trigger, .input-label');
                if(!trigger.length){ trigger = element.parent('label'); }
                var labelWidth = element.parent("p").not(".full").find("label").eq(0).width();
                error.insertAfter(trigger.length > 0 ? trigger : element)
                     .css("marginLeft", labelWidth);

                // Check if hidden inside tab
                if(element.parents(".tab").is(":hidden")){
                    var tabs = element.parents(".tabs");
                    tabs.find(".tab").hide();
                    var tab = $("#"+element.parents(".tab").attr("id"));
                    tab.show();
                    tabs.find(".tabmenu li").removeClass("selected");
                    tabs.find(".tabmenu li").eq(tab.index()-1).addClass("selected");
                }
            }
        });

        $('.tabs').bind('tabsselect', function(){
            validater.resetForm();
        });
    });
}

Solution

  • The problem is due to the fact that errorPlacement is called only once for each element which is validated.

    See this question: jQuery Validation Plugin: Invoke errorPlacement function when onfocusout, keyup and click

    They recommend using the showErrors method for any repeated validations.