0

I have a form that uses the jQuery Validation plugin. The form fields are in a series of accordion boxes, and the form error messages are displayed beneath each field. This is fine unless the field is in an accordion that is closed, and then there is no way to know that the accordion contains an error.

Is there a way to apply an error class to the accordion's title? I know that I can use something like

$("#form").validate({
    rules: {
    ...
    },
    highlight: function(element) {
        $(element).closest(".title").addClass("error");
    },
    unhighlight: function(element) {
        $(element).closest(".title").removeClass("error");
    }
});

to target the field's container, but in this case it isn't a parent.

My accordion structure is below. I need to apply the error class to the appropriate "title" div that contains the field producing the error.

<ul class="accordion">
    <li class="active">
        <div class="title panel1">
            Accordion Panel 1
        </div>
        <div class="content">
            ... form fields go here ...
        </div>
    </li>
    <li>
        <div class="title panel2">
            Accordion Panel 2
        </div>
        <div class="content">
            ... more form fields go here ...
        </div>
    </li>
    <li>
        <div class="title panel3">
            Accordion Panel 3
        </div>
        <div class="content">
            ... more form fields go here ...
        </div>
    </li>
</ul>

I also tried this with no luck:

highlight: function(element) {
    $(element).closest(".title").addClass("error");
},
unhighlight: function(element) {
    $(element).closest(".title").removeClass("error");
}

Is there a way to target the "title" divs?

1 Answer 1

2

Here the title element is the previous sibling of the .content parent

you can use

$(element).closest(".content").prev('.title').addClass("error");

or

$(element).closest("li").children('.title').addClass("error");
Sign up to request clarification or add additional context in comments.

4 Comments

this worked: $(element).closest(".content").prev(".title").addClass("error"); but it now doesn't apply the error class to the form field itself (which was the previous default behavior). Is there a way to have it add the class to both the field itself and the closest .title div?
@artmem Try $(element).closest(".content").prev('.title').addBack().addClass("error");
that adds the error class to every element within the "content" div, not just field itself.
fixed it with this: $(element).closest(".content").prev('.title').addClass("error"); $(element).addClass("error");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.