I'm trying to use jQuery validation to highlight the labels for my radio buttons only, and not the labels for my other inputs. I have a label for my radio button set called 'type'. I can't seem to get it to work!
$(document).ready(function(){
$("#healthForm").validate({
highlight: function(element, errorClass) {
$(element).addClass(errorClass)
$(element.form).find("label[for='type']")
.addClass("rad开发者_StackOverflow社区ioerror");
},
unhighlight: function(element, errorClass) {
$(element).removeClass(errorClass)
$(element.form).find("label[for='type']")
.removeClass("radioerror");
},
errorPlacement: function(error, element) {
}
});
});
I'm not really familiar with jQuery's validation plugin, but this one doesn't seem right:
$(element.form).find("label[for='type']")
Firstly, I think $(element.form)
should be $(element).closest('form')
? I could be wrong :P
Secondly, .find("label[for='type']")
has got nothing to do with the "element
" as any other elements in the same form will fetch the same label.
If the label is the sibling of the radio button, you might want to use sibling() directly.
I changed your code to the following and then it works!
$(document).ready(function() {
$("#healthForm").validate({
highlight: function(element, errorClass) {
if(element.type == 'radio') {
$(element.form).find('[name="' + element.name + '"]').each(function(){
var $this = $(this);
$this.closest('label[for="' + $this.attr('id') + '"]').addClass(errorClass);
});
}
},
unhighlight: function(element, errorClass) {
if(element.type == 'radio') {
$(element.form).find('[name="' + element.name + '"]').each(function(){
var $this = $(this);
$this.closest('label[for="' + $this.attr('id') + '"]').removeClass(errorClass);
});
}
},
errorPlacement: function(error, element) {
}
});
});
精彩评论