根据复选框验证按钮

Validate a button based on checkboxes

我正在使用 JQuery 验证库,我有一个按钮,单击该按钮会打开按钮旁边弹出的复选框列表。我想做的是,如果在单击提交时选中 none 复选框,将验证错误放在按钮上,以便将 .error class 应用于按钮,以便我可以设置按钮的样式而不是复选框的样式。这基本上就是我所拥有的

<button type="button" id="myButton" name="myButton"></button>
<ul id="myListOfCheckboxes">
    <li><input type="checkbox" id="chk1" name="checkboxList"></li>
    <li><input type="checkbox" id="chk2" name="checkboxList"></li>
    <li><input type="checkbox" id="chk3" name="checkboxList"></li>
</ul>

和验证...

$("#frmMyForm").validate({
    rules: {
        myButton: { 
            required: {
                function(element) {
                    return $("input[name='checkboxList']").is(":checked");
                }
            }
        }
    }
});

使用这个,因为输入标签的名称属性为 checkboxList 而不是 id

$("#frmMyForm").validate({
        rules: {
            myButton: { 
                  required: {
                       function(element) {
                           return $("input[name='checkboxList']").is(":checked");
                       }
              }
           }
        }
    });

place the validation error on the button, so that the .error class is applied to the button so I can set the style to the button rather than the checkbox(s).

你不能直接这样做。

您绝对不能使用此插件验证 button 元素。 jQuery Validate 仅用于验证包含实际表单数据的元素:selecttextarea、某些类型的 input 元素,以及带有 contenteditable 的某些元素属性。没有别的。

解决方法可能是验证 type="hidden" input 元素而不是 button。将隐藏元素放在按钮附近,以便验证消息显示在您需要的位置附近。请记住更改 .validate() 中的 ignore 选项以允许此操作。

由于当复选框留空时会触发错误,您实际上只是在验证复选框上的 required 规则!由于是这种情况,您可以根据复选框上的错误 类,以编程方式将错误 [​​=34=] 应用到 button