Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want jQuery validator to add a class to the form element's parent

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();
like image 898
Eystein Avatar asked Jan 21 '23 21:01

Eystein


1 Answers

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);
  }
});
like image 91
Nick Craver Avatar answered Feb 01 '23 23:02

Nick Craver