【问题标题】:Two checkboxes acting as one两个复选框作为一个
【发布时间】:2017-04-05 14:29:02
【问题描述】:

我在一个页面上有两个复选框,我希望它们只作为一个复选框。例如,我选择一个,另一个是自动选择的,反之亦然。 我设法同时选择了它们,但我似乎无法找到一种方法来一次取消选择它们。

最让我困扰的是,它可能是一段超级简单的代码,我根本不记得了。

有没有办法做到这一点?

【问题讨论】:

标签: javascript jquery checkbox


【解决方案1】:

这是你要找的吗?

$(".test").change(function () {
    $(".test").attr("checked", this.checked);
  });

<input type='checkbox' class='test'>A<br />
<input type='checkbox' class='test'>B<br />

【讨论】:

  • 请添加一些解释,说明此代码为何/如何帮助 OP。这将有助于为未来的观众提供一个可以从中学习的答案。请参阅this Meta question and its answers 了解更多信息。
  • 另外,应该使用prop('checked', this.checked) 作为布尔属性值。
【解决方案2】:

这是纯javascript的解决方案:

// Select all checkboxes using `.checkbox` class
var checkboxes = document.querySelectorAll('.checkbox');

// Loop through the checkboxes list
checkboxes.forEach(function (checkbox) {
    // Then, add `change` event on each checkbox
    checkbox.addEventListener('change', function(event) {
        // When the change event fire,
        // Loop through the checkboxes list and update the value
        checkboxes.forEach(function (checkbox) {
            checkbox.checked = event.target.checked;
        });
    });
});
<label><input type="checkbox" class="checkbox"> Item 1</label>
<br>
<label><input type="checkbox" class="checkbox"> Item 2</label>

【讨论】:

    【解决方案3】:

    $(document).ready(function() {
    	$('#check_one').change(function() {
      	$('#check_two').prop('checked', $('#check_one').prop('checked'));
      });
      
    	$('#check_two').change(function() {
        $('#check_one').prop('checked', $('#check_two').prop('checked'));
      });  
    });
    <form>
    <label>Simple checkbox</label>
    <input type="checkbox" id="check_one" />
    <label>Complicated checkbox</label>
    <input type="checkbox" id="check_two" />
    </form>

    假设您有两个名称不同但协同工作的复选框,则此代码将起作用

    【讨论】:

      【解决方案4】:

      html:

      <input type="checkbox" id="1" class="handleAsOne">
      <input type="checkbox" id="2" class="handleAsOne">
      

      javascript (jquery):

      $('.handleAsOne').on('change'){
         $('.handleAsOne').prop('checked', false);
         $(this).prop('checked', true);
      }
      

      如果我正确理解了你的问题,你正在寻找这样的东西。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-10
        • 1970-01-01
        • 2023-03-13
        相关资源
        最近更新 更多