views:

72

answers:

2

How do I use jQuery validator to add/remove a classname (e.g. validate) on the form element's parent <li> so I can style everything related to that element by only setting the one classname?

The markup is

<li class="validate">
    <label for="product">Product of interest <abbr title="Required field">*</abbr></label>
    <input id="product" type="text" name="product" value="" placeholder="e.g. school bench" class="required" minlength="2">

    <!-- Hidden by CSS unless parent has 'validate' class -->
    <label for="product" class="description">Please name a product.</label> 
</li>

and the default jQuery is

$("#commentForm").validate();
A: 
$(".validate").parent().removeClass('YouCSSClass');
$(".validate").parent().addClass('YouCSSClass');

Also you can see some examples here http://api.jquery.com/parent/ about the add remove css classes refer to http://api.jquery.com/addClass/

Teddy
No dot required in `removeClass` and `addClass`.
nikc
But how do I actually `addClass` upon `.validate()`? Something like `$("#commentForm").validate().parent().addClass("validate");` won't work.
Eystein
I couldn't understand which element's parent you want to find. If you want the parent of the `<li class="validate">` you can give it an ID to identify it.
Teddy
I'd like to find the `li` (which I've hardcoded to `<li class="validate">` in my question). I'm assuming there is a way to do it with the jQuery validator script itself, rather than writing an extra layer on top of it..?
Eystein
Well you can set the error and valid class using the validate method like this `$("#commentForm").validate({ validClass: ""}) and $("#commentForm").validate({ errorClass: "validate"})` Does this help?
Teddy
Thanks, but I ended up using Nick Craver's solution.
Eystein
+2  A: 

Use the highlight and unhighlight options here to override where the errorClass (or validClass) gets applied:

$("#commentForm").validate({
  highlight: function(element, errorClass, validClass) {
    $(element).closest('.validate').addClass(errorClass).removeClass(validClass);
  },
  unhighlight: function(element, errorClass, validClass) {
    $(element).closest('.validate').addClass(validClass).removeClass(errorClass);
  }
});

By default, the errorClass is "error" and get applied directly on the input element. For a better illustration, this is the default validate functions, when you don't provide these options to .validate(), here's what happens:

$("#commentForm").validate({
  errorClass: "error",
  validClass: "valid",
  highlight: function( element, errorClass, validClass ) {
    $(element).addClass(errorClass).removeClass(validClass);
  },
  unhighlight: function( element, errorClass, validClass ) {
    $(element).removeClass(errorClass).addClass(validClass);
  }
});
Nick Craver
Thank you, this was what I was looking for.
Eystein