Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

jquery - Placing error message for a checkbox array

I am using the Validation Plugin for jQuery and it works wonders. Except when I have a group of checkboxes...the error messages will display right after the first checkbox...like so:

alt text

<tbody>
     <c:forEach items="${list}" var="item">
        <tr>
          <td align="center">
             <input type="checkbox" name="selectItems" value="<c:out value="${item.numberPlate}"/>" />
          </td>
          <!--some other columns-->
         </tr>
      </c:forEach>                       
</tbody>

------------------------------EDITED-------------------------

I found that I can use errorPlacement , but I have no idea how to show ONLY the error message of the checkbox array in the table footer or somewhere else inside the second fieldset.

Hope you can help me out.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 !


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...