【发布时间】:2014-05-29 18:21:12
【问题描述】:
我在表单上使用 jQuery 验证插件,但在设置复选框组的样式时遇到问题。该插件将一个类 (.error) 添加到我用来更改输入颜色的无效输入中。
问题在于,当您对一组复选框进行验证时,它只会将该类添加到该组中的第一个复选框。我希望它以与无线电输入相同的方式运行。 When none are selected they all get the error class, then when one is selected they all get the valid class.
DEMO:简化的测试用例,带有复选框输入组和单选输入组。
在演示中提交表单,您可以看到只有第一个复选框获得了错误类,但所有无线电输入都获得了它。
// Example html
<form action="#" id="form" method="post">
<ul>
<li>
<input type="checkbox" name="checkbox[]" id="checkbox1">
<label for="checkbox1">Mike</lable>
</li>
<li>
<input type="checkbox" name="checkbox[]" id="checkbox2">
<label for="checkbox2">November</lable>
</li>
<li>
<input type="checkbox" name="checkbox[]" id="checkbox3">
<label for="checkbox3">Oscar</lable>
</li>
</ul>
<input type="submit" value="submit">
</form>
// Validation Plugin Config
$(document).ready(function() {
$("#form").validate({
rules: {
"checkbox[]": {
required: true,
minlength: 1
},
radio: "required",
},
validClass: "js-valid",
errorLabelContainer: ".js-errors",
errorElement: "li",
messages: {
"checkbox[]": "Please select at least one checkbox",
radio: "Please choose from the Radio Group",
},
});
});
我在 jQuery 论坛中找到了this suggestion,但是当我尝试这样做时,错误类似乎应用于所有复选框,但选择一个并没有删除它。
【问题讨论】:
标签: jquery html validation checkbox