我在HTML中有两个复选框,默认情况下这两个复选框都是选中的。用户可以取消选择它们。
现在,我希望经常选中这两个复选框中的至少一个。也就是说,用户可以同时选中这两个选项,也可以只选中其中一个,但不能同时取消选择。
(背景信息:它们连接到一个隐藏/显示-jQuery-切换,取消选择这两个都会使整个页面为空。)
你知道怎么做吗(用复选框或单选按钮-或者其他什么)?如果您能帮忙,我将不胜感激!
发布于 2018-08-14 19:42:02
既然你说过使用jQuery:
本质上,我们只是添加一个事件侦听器,如果没有选中任何框,我们就会防止最后一个框被取消选中。
<input type="checkbox" class="at-least-one">
<input type="checkbox" class="at-least-one">
<script type="text/javascript">
$(document).on("click", ".at-least-one", function(evt) {
// This is technically run after the checked value changes, so we're checking
// if there is no more boxes checked after we uncheck this one. If there is
// no more, then prevent the event, setting the box back to checked.
if ($(".at-least-one:checked").length == 0) {
evt.preventDefault()
return false
}
})
</script>
发布于 2018-08-14 19:58:52
如果选中复选框的数量为假值(0
),则可以向这两个复选框和return false
添加click
事件侦听器。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>One checkbox must always be checked</p>
<input type="checkbox" name="checkone" checked>
<input type="checkbox" name="checkone" checked>
<script>
$('input[name=checkone]').click(function(e){
if(!$('input[name=checkone]:checked').length){
return false;
}
});
</script>
https://stackoverflow.com/questions/51848610
复制相似问题