验证至少一个子复选框,对应于复选框数组的选中元素



我在具有一组嵌套复选框组的表单上实现了jQuery验证。主复选框是复选框数组的一个元素。如果选中了主复选框,则必须至少选中子复选框。子复选框位于div 中,id 是使用主复选框的值生成的。

以下代码有效,但我很确定这可以简化更多。我请这里的专家使这项工作做得更好。提前谢谢。

$.validator.addMethod("atLeastOne", function(value, element) {
    var flag = true;
    $('.mod_check').each(function(){ 
    if (this.checked){
        if($('#actions_'+$(this).val()).find('input[type=checkbox]:checked').length == 0)
           flag = false;
    }
});
return flag;
}, "Select at least one of the actions");

一种改进方法是在遇到任何一个未选中的子复选框时从 $.each 中断。

$.validator.addMethod("atLeastOne", function(value, element) {
var flag = true;
$('.mod_check').each(function(){ 
if (this.checked){
    if($('#actions_'+$(this).val()).find('input[type=checkbox]:checked').length == 0)
       flag = false;
       return;
}
});
return flag;
}, "Select at least one of the actions");

因此,不需要其余的迭代。

最新更新