I am using the jQuery Validate plugin, and can never find a good way to display errors for checkboxes. I'd like to highlight all of the checkbox labels in red if none are selected, and decide to do this by adding an error class to the div that contains the checkboxes and checkbox labels. However, it doesn't seem to be adding the class. Am I not selecting the div correctly?
HTML:
<div class="left-aligned indent">
<label id="id_label" for="id" class="label">Items:</label>
<div class="select-group">
<input type="checkbox" name="items" value="1" id="item_1" />
<label class="checkbox">Item #1</label><br />
<input type="checkbox" name="items" value="1" id="item_2" />
<label class="checkbox">Item #2</label><br />
<input type="checkbox" name="items" value="1" id="item_3" />
<label class="checkbox">Item #3</label><br />
</div>
</div>
Javascript:
$().ready(function() {
$('#addForm').validate({
rules: {
"items": {
required: true,
minlength: 1
}
},
errorPlacement: function(error, element) {
if (element.is(':checkbox')) {
$(this).prev("div").addClass('checkbox-error');
}
else {
return true;
}
}
});
});
CSS:
.error {
background-color: #FF898D;
border: 1px solid #000;
}
.checkbox-error {
color: #FF898D;
}
This should work:
$('#myform').validate({
highlight: function(element) {
$(element).parent().addClass("field-error");
},
unhighlight: function(element) {
$(element).parent().removeClass("field-error");
}
});
Checkout the documentation for more options:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With