David
David

Reputation: 1

How to hide and show things in jQuery based on the existence of other elements?

I have a form where the jquery validation plugin will generate div tags with the class "error" if there is a validation error on form submission. If any such divs exist I want to display an additional error message above the form. This message is stored like so:

<p class="topError">Oops errors found!</p>

<form id="myForm">

// blah blah

</form>

if the error divs weren't generated by the plugin, I would do something like:

if (('#myForm div.error').length() > 0 ) {
   $('p.topError').show();
}

In this situation how can I solve this and I also need the top error to vanish the moment there isn't any error divs in the form.

Upvotes: 0

Views: 99

Answers (2)

Adolph Trudeau
Adolph Trudeau

Reputation: 361

The showErrors callback of the plugin may be helpful, depending on what exactly you are doing. The plugin doesn't seem to have an event to bind on, so you could bind a form event and then perform the div.error check based on that.

$("#myForm input").bind("blur",function(){
    if (('#myForm div.error').length() > 0 ) {
        $('p.topError').show();
    } else {
        $('p.topError').hide();
    }
})

Upvotes: 0

Naftali
Naftali

Reputation: 146302

if ($('#myForm div.error').length > 0 ) {
   $('p.topError').show();
}
else {
   $('p.topError').hide();
}

Upvotes: 1

Related Questions