为复选框数组放置错误消息

发布于 2024-10-09 08:14:50 字数 754 浏览 0 评论 0原文

我正在使用 jQuery 的验证插件,它的效果非常好。除非我有一组复选框...错误消息将在第一个复选框之后显示...就像这样:

alt文本

<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>

------------------------------已编辑-------------- ------------

我发现我可以使用 errorPlacement ,但我不知道如何显示错误消息表页脚或第二个字段集中其他位置的复选框数组的位置。

希望你能帮助我。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

孤云独去闲 2024-10-16 08:14:50

为什么不使用自定义验证方法?像这样的东西:

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>

由于 jQuery Validate 插件还可以验证元素(如果方法名称以 class 形式出现),只需简单地在所有复选框上输出 .one_required 类。

请参阅带有多个复选框的 JSFiddle 上的工作演示

编辑:

这里是您自己的代码,并实现了上述解决方案。

希望这有帮助!

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 !

怀里藏娇 2024-10-16 08:14:50

您可以使用 errorLabelContainer 配置选项..
定义一个带有像 errorMessages 这样的 id 的 div,然后更改您的验证方法调用,如下所示:

$("form").validate({
   errorLabelContainer: $("#errorMessages"),
     rules: ..... your rules

现在所有错误消息都将显示在该 div 中。
编辑:更新了以下答案以反映问题的更新:
要更改错误消息显示的位置,我可以考虑使用 errorPlacement 配置参数。
你可以使用类似的东西:
定义一个 div 或 ap 并继续将复选框的消息附加到该元素。

$("form").validate({
errorPlacement:function(error,element) {
    if (element.attr("name") == "selectItems") {
        //Add Code to append the error message to a predefined element
        $("#errorDiv").html("");
        $("#errorDiv").append("<YOUR_CUSTOM_MESSAGE>");
    } else { 
        error.insertAfter(element);
    }
  },
  rules: ..... your rules
});

jsFiddle URL: http://jsfiddle.net/Z8hWg/28/

编辑:
将您的 JavaScript 更改为如下:

<script type="text/javascript">
    $(document).ready(function(){        
                var formValidator = {};
                $("#Date").datepicker();       
                formValidator = $("#form1").validate({
                        errorPlacement:function(error,element) {
                                if (element.attr("name") == "selectedItems") {
                                                //Add Code to append the error message to a predefined element
                                        $("#errorDiv").html("Select at least one vehicle");
                                } else {
                                        error.insertAfter(element);
                                }
                        },

                        rules: {
                                avgTime:{
                                        required:true,
                                        number:true
                                },

                                selectedItems:
                                {
                                        required:true
                                },
                                Date:{
                                        required:true,
                                        date:true
                                }

                        },    
                        //onclick: true,
                        submitHandler: function(form) {
                                $("#errorDiv").html("");
                                form.submit();
                        }

                });       
                $("input[name=selectedItems]").bind("change", function() {
                        var me = $(this);
                        var scoper = me.parent().parent();
                        var otherInputs = $("input[name^=mileage]", scoper);
                        otherInputs.attr("disabled", !this.checked);
                        otherInputs.attr("value","");
                        if (this.checked)
                        {
                                otherInputs.addClass('required number');
                                $("#errorDiv").html("");
                        }
                        else
                        {
                                otherInputs.removeClass("required number");
                        }
                        formValidator.element("input[name=selectedItems]");
                });


        });  
</script>

You can use errorLabelContainer configuration option..
define a div with an id like errorMessages and then change your validate method call as follows:

$("form").validate({
   errorLabelContainer: $("#errorMessages"),
     rules: ..... your rules

Now all the error messages will be displayed in the div.
Edit: Updated the answer below to reflect the updates to the question:
To change the location of error messages displayed, I can think of using the errorPlacement config parameter.
You can use something like:
Define a div or a p and keep appending the messages for the checkboxes to this element.

$("form").validate({
errorPlacement:function(error,element) {
    if (element.attr("name") == "selectItems") {
        //Add Code to append the error message to a predefined element
        $("#errorDiv").html("");
        $("#errorDiv").append("<YOUR_CUSTOM_MESSAGE>");
    } else { 
        error.insertAfter(element);
    }
  },
  rules: ..... your rules
});

jsFiddle URL: http://jsfiddle.net/Z8hWg/28/

EDIT:
Change your javascript to as follows:

<script type="text/javascript">
    $(document).ready(function(){        
                var formValidator = {};
                $("#Date").datepicker();       
                formValidator = $("#form1").validate({
                        errorPlacement:function(error,element) {
                                if (element.attr("name") == "selectedItems") {
                                                //Add Code to append the error message to a predefined element
                                        $("#errorDiv").html("Select at least one vehicle");
                                } else {
                                        error.insertAfter(element);
                                }
                        },

                        rules: {
                                avgTime:{
                                        required:true,
                                        number:true
                                },

                                selectedItems:
                                {
                                        required:true
                                },
                                Date:{
                                        required:true,
                                        date:true
                                }

                        },    
                        //onclick: true,
                        submitHandler: function(form) {
                                $("#errorDiv").html("");
                                form.submit();
                        }

                });       
                $("input[name=selectedItems]").bind("change", function() {
                        var me = $(this);
                        var scoper = me.parent().parent();
                        var otherInputs = $("input[name^=mileage]", scoper);
                        otherInputs.attr("disabled", !this.checked);
                        otherInputs.attr("value","");
                        if (this.checked)
                        {
                                otherInputs.addClass('required number');
                                $("#errorDiv").html("");
                        }
                        else
                        {
                                otherInputs.removeClass("required number");
                        }
                        formValidator.element("input[name=selectedItems]");
                });


        });  
</script>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文