Placing error message for a checkbox array

Why not use a custom validation method ? Something like this:

jQuery:

// The custom validation method, returns FALSE (invalid) if there are
// no checkboxes (with a .one_required class) checked
$.validator.addMethod("one_required", function() {
    return $("#myform").find(".one_required:checked").length > 0;
}, 'Please select at least one vehicle.');

$("#myform").validate({
    // Use the built-in errorPlacement function to place the error message
    // outside the table holding the checkboxes if they are the ones that
    // didn't validate, otherwise use the default placement.
    errorPlacement: function(error, element) {
        if ($(element).hasClass("one_required")) {
            error.insertAfter($(element).closest("table"));
        } else {
            error.insertAfter(element);
        }
    }
});

HTML:

<form id="myform">
    <!-- table, rows, etc -->
    <td align="center"><input type="checkbox" class="one_required" name="selectItems[]" value="NA245852" /></td>
    <td>NA245852</td>
    <!-- more rows, end table, etc -->
    <br/>
    <input type="submit" value="Go, baby !">
</form>

Since the jQuery Validate plugin can also validate an element if the method name is present as a class, simply output the .one_required class on all checkboxes.

See a working demo on JSFiddle with multiple checkboxes.

EDIT:

Here’s your own code with the above solution implemented.

Hope this helps !

Leave a Comment

tech