HTML(或jQuery):选中一个或两个复选框(或单选按钮)

时间:2018-08-14 19:33:45

标签: javascript jquery html checkbox radio

我有两个HTML复选框,它们都是默认选中的。用户可以取消选择它们。

现在,我希望至少两个复选框中的至少一个始终处于选中状态。也就是说,用户既可以选中两个用户,也可以只选中其中一个,但是他们不能同时取消选择两者。

(背景信息:它们连接到hide / show-jQuery-toggle,并且取消选择这两个选项会使整个页面为空。)

您知道如何执行此操作(使用复选框或单选按钮-或其他方法)吗?感谢您的帮助!

3 个答案:

答案 0 :(得分:0)

自从您说使用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>

答案 1 :(得分:0)

HTML

onCreate

JavaScript

<div>
  <input type="radio" data-bind="div1" name="radioGroup" value="both" class="radioGroup">
  <input type="radio" data-bind="div2" name="radioGroup" value="Option 1" class="radioGroup">
  <input type="radio" data-bind="div3" name="radioGroup" value="Option 2" class="radioGroup">
</div>

答案 2 :(得分:0)

如果选中的复选框的数量为假值(click),则可以为它们{{1}和return false都添加一个0事件监听器。

<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>