正确,此主题之前已在validation for at least one checkbox(及相关演示网站http://jsfiddle.net/RGUTv/)进行了讨论。所以我复制了解决方案,但它似乎没有工作,我无法弄清楚为什么。控制台显示在validate()调用之后根本没有触发实现的函数。我假设错误只能是我的html代码,但具体是什么错误?
有什么建议吗?
提前致谢。
Html代码:
<input type="checkbox" id="check0" name="productselection0" value="productselected0" class="require-one">
<input type="checkbox" id="check1" name="productselection1" value="productselected1" class="require-one">
<input type="checkbox" id="check2" name="productselection2" value="productselected2" class="require-one">
Javascript代码(来自validation for at least one checkbox解决方案的1对1副本):
<script>
$(document).ready(function() {
$.validator.addMethod('require-one', function(value) {
console.log("addMethod triggered");
return $('.require-one:checked').size() > 0;
}, 'Please check at least one box.');
var checkboxes = $('.require-one');
var checkbox_names = $.map(checkboxes, function(e, i) {
return $(e).attr("name")
}).join(" ");
$("#myForm").validate({
groups: {
checks: checkbox_names
},
errorPlacement: function(error, element) {
if (element.attr("type") == "checkbox")
error.insertAfter(checkboxes.last());
else error.insertAfter(element);
}
}); //validate()
}); //function
</script>
答案 0 :(得分:0)
在additional-method.js
file中,有一个名为require_from_group
的方法可以执行您所描述的操作...从选定的组中生成指定数字的输入元素required
输入元素。 (确保使用修复了错误的最新版本(1.11.1))
$(document).ready(function () {
$('#myform').validate({
rules: {
productselection0: {
require_from_group: [1, '.require-one']
},
productselection1: {
require_from_group: [1, '.require-one']
},
productselection2: {
require_from_group: [1, '.require-one']
}
},
groups: {
checks: "productselection0 productselection2 productselection3"
}
});
});