我正在尝试创建一个函数来检查是否所有复选框都未选中.我有一个类似的文本框功能.因为我以前没有使用过复选框,所以我不确定如何改编它除了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)
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)
或者,如果您想要的是一个布尔值,以指示是否选中了任何复选框,以便在函数中使用:
var isChecked = document.querySelectorAll('input:checked').length === 0 ? false : true;
return isChecked;
Run Code Online (Sandbox Code Playgroud)
当然,您可以避免创建变量并简单地返回三元的结果; 我只使用变量来尝试清楚地说明了我正在返回/测试的内容.
参考:
这是一个简短且非常简单的示例(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)
| 归档时间: |
|
| 查看次数: |
33442 次 |
| 最近记录: |