Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Validate - Add Error Class to Parent Div

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;
}
like image 591
Michael Avatar asked Oct 29 '11 20:10

Michael


1 Answers

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:

  • http://jqueryvalidation.org/validate/
like image 94
Luis Evrythng Avatar answered Oct 09 '22 21:10

Luis Evrythng