Dirty Bird Design
Dirty Bird Design

Reputation: 5523

Add class if form field is invalid

Using jQuery validation for ajax form submission and I would like to add a class to the errorContainer if any of the text inputs have a class 'error'. Seems simple but I think it's a scope issue?

if ($('#myInput').hasClass('error')) { 
  $('#errorContainer').addClass('foo'); 
}

I have placed this outside the submit handler, inside submit handler, outside of validation call, inside validation call... all to no avail. Has anyone done this simple task with success?

Upvotes: 0

Views: 4866

Answers (3)

Cymen
Cymen

Reputation: 14419

You can do this:

if ($('input[type=text].error').length > 0) { 
  $('#errorContainer').addClass('foo'); 
}

The selector $('input[type=text].error') is going to return an array-like object even if there is only one match. So asking an array if it hasClass('error') doesn't make sense.

What you really want to do is put a container around your elements you want to check for the error class. You might already have a container like the form (if it is all the inputs on the form). Then you can do something like this:

<form id="myForm">
  <input type="text" name="a" />
  <textarea name="b"></textarea>
  <input type="submit" value="Submit" />
</form>

With JavaScript:

$(':input.error', '#myForm').length > 0

Here is an example jsfiddle. Note that using the :input selector will more input types than just input which may be what you want.

Upvotes: 2

wirey00
wirey00

Reputation: 33661

You can just use toggleClass and pass in the condition

$('#errorContainer').toggleClass('foo',$('input[type=text].error').length > 0);

So if there are any with class error.. add class foo.. else remove class foo

Upvotes: 1

Anthony Grist
Anthony Grist

Reputation: 38345

Most functions that return a value (such as .val(), .hasClass(), etc) will only act on the first element in the group of selected elements contained within the jQuery object.

Generally in these cases what you'd need to do is use the .each() function to iterate over all of the elements, and do the test for each of them.

However, since you're testing for a class, you can modify your condition as detailed in Cymen's answer.

Upvotes: 1

Related Questions