jqueryjquery-validatefindfirst

jQuery. Function to find first div containing invalid fields


I have a form divided into three tabs and validate it with jQuery validation plugin. User can switch between tabs with links. After submit button is pushed and validation failed, error class is being added to links which corresponding tabs/containers has errors. This made with next function:

function treatFormLinks () {
    $('.formTab').each(function(){
        $("#" + this.id + "Link").toggleClass('hasErrors', !$('input, select, textarea', this).valid());
    });     
};
$("#Submit").click(function () {
    $('.FormNavi a').removeClass('hasErrors');
    treatFormLinks();
});

Here's html example, just to explain the idea how it works:

<a href="#" id="OneLink">Link 1</a>
<a href="#" id="OneLink">Link 2</a>
<a href="#" id="OneLink">Link 3</a>

<form>
    <div class="formTab" id="One">... form fields ...</div>
    <div class="formTab" id="Two">... form fields ...</div>
    <div class="formTab" id="Three">... form fields ...</div>
</form>

What I need is to find first div, which contains invalid fields and the show this one. Let's say #One and #Three divs' fields are valid and div #Three is visible. What I want is to show #Two after pushing submit button.

Thank you!


Solution

  • Show the div right after you set the link.

    function treatFormLinks () {
        var alreadydisplayed = false;
        $('.formTab').each(function(){
            $("#" + this.id + "Link").toggleClass('hasErrors', !$('input, select, textarea', this).valid());
            alreadydisplayed?void(0):$(this).css("display","");//if an invalid tab has already been displayed, do nothing
            alreadydisplayed = true;
        });     
    }