html 在一组中只选择一个复选框

标签 html checkbox

那么我怎样才能只允许用户选择一个复选框呢?

我知道单选按钮是“理想的”,但就我的目的而言......它不是。

我有一个字段,用户需要在其中选择两个选项中的一个或一个,但不能同时选择两个。问题是我需要我的用户也能够取消选择他们的选项,这就是单选按钮失败的地方,因为一旦你选择了组,你就必须选择一个选项。

我将通过 php 验证信息,但我仍然希望限制用户只能提供一个答案。

最佳答案

此代码段将:

  • 允许像单选按钮一样分组
  • 像 radio 一样行动
  • 允许全部取消选择

// the selector will match all input controls of type :checkbox
// and attach a click event handler 
$("input:checkbox").on('click', function() {
  // in the handler, 'this' refers to the box clicked on
  var $box = $(this);
  if ($box.is(":checked")) {
    // the name of the box is retrieved using the .attr() method
    // as it is assumed and expected to be immutable
    var group = "input:checkbox[name='" + $box.attr("name") + "']";
    // the checked state of the group/box on the other hand will change
    // and the current value is retrieved using .prop() method
    $(group).prop("checked", false);
    $box.prop("checked", true);
  } else {
    $box.prop("checked", false);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


<div>
  <h3>Fruits</h3>
  <label>
    <input type="checkbox" class="radio" value="1" name="fooby[1][]" />Kiwi</label>
  <label>
    <input type="checkbox" class="radio" value="1" name="fooby[1][]" />Jackfruit</label>
  <label>
    <input type="checkbox" class="radio" value="1" name="fooby[1][]" />Mango</label>
</div>
<div>
  <h3>Animals</h3>
  <label>
    <input type="checkbox" class="radio" value="1" name="fooby[2][]" />Tiger</label>
  <label>
    <input type="checkbox" class="radio" value="1" name="fooby[2][]" />Sloth</label>
  <label>
    <input type="checkbox" class="radio" value="1" name="fooby[2][]" />Cheetah</label>
</div>

关于html 在一组中只选择一个复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9709209/

相关文章:

Javascript将变量写入div

html - 如何将多个类分配给 HTML 容器?

html - 我将如何修改 <div> 元素以同时在网页上居中并保持其大小属性?

html - 提交按钮周围带有渐变的奇怪边框。我该如何删除?

java - 如何从动态添加的复选框中获取 id 及其值

angularjs - Angular Material 复选框 - 将功能添加到 ng-checked

jquery - 在窗口调整大小时自动调整右侧容器的宽度

Android ListView 复选框选择

android - 我看不到 ScrollView 中复选框的文本

c# - 当使用MVVM + WP7 + LongListSelector选中对号时,如何调用服务器