如何检查是否取消选中所有复选框

use*_*429 14 html javascript

我正在尝试创建一个函数来检查是否所有复选框都未选中.我有一个类似的文本框功能.因为我以前没有使用过复选框,所以我不确定如何改编它除了input[type=text]改为input[type=checkbox].

谁能帮我吗?谢谢.

var textinputs = document.querySelectorAll('input[type=text]'); 
var empty = [].filter.call( textinputs, function( el ) {
     return !el.value
});

    if (textinputs.length == empty.length) {
        alert("None filled");
        return false;
}
Run Code Online (Sandbox Code Playgroud)

end*_*rif 17

以下应该做的伎俩:

var textinputs = document.querySelectorAll('input[type=checkbox]'); 
var empty = [].filter.call( textinputs, function( el ) {
   return !el.checked
});

if (textinputs.length == empty.length) {
    alert("None filled");
    return false;
}
Run Code Online (Sandbox Code Playgroud)

  • document.querySelectorAll("#divWeeklyDays input[type='checkbox']:checked"); (2认同)

Dav*_*mas 16

鉴于您可以使用,您可以简化一点querySelectorAll():

var checked = document.querySelectorAll('input:checked');

if (checked.length === 0) {
    // there are no checked checkboxes
    console.log('no checkboxes checked');
} else {
    // there are some checked checkboxes
    console.log(checked.length + ' checkboxes checked');
}
Run Code Online (Sandbox Code Playgroud)

JS Fiddle(未选中复选框).

JS Fiddle(选中了一些复选框).

或者,如果您想要的是一个布尔值,以指示是否选中了任何复选框,以便在函数中使用:

var isChecked = document.querySelectorAll('input:checked').length === 0 ? false : true;
return isChecked;
Run Code Online (Sandbox Code Playgroud)

概念验证演示.

当然,您可以避免创建变量并简单地返回三元的结果; 我只使用变量来尝试清楚地说明了我正在返回/测试的内容.

参考:

  • @user280109:这是因为 `[checked]` 匹配该属性,当元素未选中/选中时该属性不会更新;而 `:checked` 匹配已检查的属性(显然,当它被检查时)。 (2认同)

Zli*_*tus 7

这是一个简短且非常简单的示例(Vanilla Javascript):

if (document.querySelectorAll('input[type="checkbox"]:checked').length === document.querySelectorAll('input[type="checkbox"]').length) {
    console.log('All checkboxes are checked');
} else {
    console.log('Some checkboxes are not checked');
}
Run Code Online (Sandbox Code Playgroud)

这里使用 jQuery 语法:

if ($('input[type="checkbox"]:checked').length === $('input[type="checkbox"]').length) {
    console.log('All checkboxes are checked');
} else {
    console.log('Some checkboxes are not checked');
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用:not() 伪选择器

if (document.querySelectorAll('input[type="checkbox"]:not(:checked)').length) {
    console.log('Some checkbox are not checked');
}
Run Code Online (Sandbox Code Playgroud)