Html代码
<div class="answer">
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</div>
<div class="answer">
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</div>
<button>check</button>
jQuery代码
$('button').click(function(){
var checkedboxes = $('.answer :checkbox:checked').length;
if (checkedboxes === 0){
alert('At least 1 checkbox must be checked from this div!');
}
});
但是我的代码没有检查每个<div class='answer'>
答案 0 :(得分:2)
尝试,
if ($('.answer').filter(function(){ return $(this).find(':checked').length === 0 }).length > 0 ) {
alert('At least 1 checkbox must be checked from this div!');
}
答案 1 :(得分:2)
您可以遍历所有.answer
并检查其中是否没有选中复选框:
$('button').click(function(){
$('.answer').each(function() {
if($(this).find(':checkbox:checked').length === 0) {
alert('At least 1 checkbox must be checked from this div!');
}
});
});
<强> Fiddle Demo 强>
答案 2 :(得分:0)
试试这个:
$('button').click(function(){
$('.answer').each(function() {
if (!$(this).find('input:checked').length ) {alert('At least 1 checkbox must be checked from this div!');
return false;
}});});
<强> Working Demo 强>
答案 3 :(得分:0)
选择器中的问题是您选择了所有答案.answers
要选择有问题的块,而不循环所有答案,选择器会更复杂:
$('button').click(function(){
// check if there is an '.answer' which does NOT have checked checkbox.
var checkedboxes = $(".answer:not(:has(> input:checkbox:checked))").length;
if (checkedboxes > 0){
alert('At least 1 checkbox must be checked from this div!');
}
});