我有一个在检查时会展开的表单。当表单展开时,有多个复选框 - 我需要确保此时至少选中一个复选框。我有以下 html/js 代码,在未选中任何复选框时可以工作,但是当我选择主复选框时,错误就会消失。当在展开的表单中选择任何复选框时,错误应该消失。
$(document).ready(function () {
$('#checkBtn').click(function() {
checked = $("input[type=checkbox]:checked").length;
if(!checked) {
alert("You must check at least one checkbox.");
return false;
}
});
});
.inputs {
display: none;
}
.foo:checked + .inputs {
display: initial;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form action="foo">
<input type="checkbox" class="foo"> Pre-designed contour:
<div class="inputs">
<input type="checkbox" name="contour" value="fiveSeven" id="fiveSeven"> 5x7
<input type="checkbox" required id="sixEight"> 6x8
<input type="checkbox" required id="sixNine"> 6x9
</div>
</form>
<input type="button" value="Test Required" id="checkBtn">
最佳答案
您正在使用以下行检查代码中是否有选中的复选框:
checked = $("input[type=checkbox]:checked").length;
相反,您应该检查在选择主复选框时显示的 div 中的复选框。
解决方案:
单击提交按钮时检查主复选框的状态。如果被选中,则检查显示的 div 中选中的复选框的数量。
- 为主复选框提供 id 属性值(例如 mainCheckbox ),并为 div 中显示的所有复选框提供相同的类值(例如 childCheckbox)。
在按钮单击事件中,检查主复选框的状态。
if ($('#mainCheckbox')[0].checked) { //check for selected checkboxes in div }
如果选中,请检查选定的复选框
if ($('#mainCheckbox')[0].checked) { if(!$('.childCheckbox:checked').length) { alert("You must check at least one checkbox."); return false; } }
关于javascript - 展开表单时,至少选中表单中的一个复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45989099/