簡體   English   中英

驗證至少一個子復選框,該復選框對應於復選框數組的已選中元素

[英]Validating at least one child checkbox, corresponding to a checked element of a checkbox array

我在具有一組嵌套復選框組的表單上實現了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");

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM