简体   繁体   English

两个复选框合而为一

[英]Two checkboxes acting as one

I have two checkboxes on a page and I want them to act as only one. 我在页面上有两个复选框,我希望它们仅充当一个复选框。 For example, I select one, and the other is selected automatically, and vice-versa. 例如,我选择一个,另一个被自动选择,反之亦然。 I've managed to select both of them at once, but I can't seem to figure out a way to deselect them at once. 我设法一次选择了这两个选项,但似乎无法找出一种立即取消选择它们的方法。

And what's bothering me the most, is that it's probably a super simple line of code that I'm simply not remembering. 最让我困扰的是,这可能是我根本不记得的超简单代码行。

Is there a way to do this? 有没有办法做到这一点?

Is this what you're looking for? 这是您要找的东西吗?

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

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

Here is a solution in pure javascript: 这是纯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> 

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

Assuming you have two checkboxes named differently but working in concert, this code would work 假设您有两个复选框的名称不同,但协同工作,则此代码将起作用

html: HTML:

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

javascript (jquery): javascript(jquery):

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

if i understood your question correctly you are looking for something like this. 如果我正确理解了您的问题,那么您正在寻找这样的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM