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 eleme开发者_JAVA百科nt 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();
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);
}
});
$(".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/
精彩评论