当一个选项(复选框)处于打开状态时,是否可以单击多个复选框,而当它关闭时,您一次只能选择一个?

时间:2020-03-05 11:12:10

标签: javascript jquery reactjs checkbox bootstrap-4

我希望能够执行上图中的功能。但是,它将无法正常工作。

enter image description here

$("#customSwitches").click(function() {
  var $this = $(this);
  if ($this.data('clicked')) {
    alert("not element clicked");
    $this.data('clicked', false);
    $(document).on('click', "#radio1, #radio2, #radio3, #radio4").not(this).prop('checked', false);
    });
  } else {
    alert("element clicked");
    $this.data('clicked', true);
  }
});

2 个答案:

答案 0 :(得分:1)

在组中复选框的每次单击中,您可以检查checked的{​​{1}}属性。如果未选中,则可以从组中计算#customSwitches个复选框的长度,如果大于checked,则可以阻止默认事件。

单击1时,可以重置组中的所有复选框。

您可以尝试以下方式:

#customSwitches
$(".vehicle").click(function(e){
    if($('#customSwitches').is(':not(:checked)')){
      if($('.vehicle:checked').length > 1){
        alert('You can not check multiple');
        e.preventDefault();
      }
    }
});

$("#customSwitches").click(function(e){
   $(".vehicle").prop('checked', false);
});

答案 1 :(得分:0)

您当前的代码存在语法问题,并使用了嵌套事件处理程序,这不是一个好的设计模式。

从基本意义上讲,您正在尝试根据第一个复选框状态构建动态复选框限制器。为此,只需确定第一个框是否已选中,然后计算已选中区域的数量以查看其是否超出限制。如果是这样,则禁止选中当前框。试试这个:

let $allowMulti = $('#allow_multi').on('change', function() {
  if (!this.checked)
    $('.region').prop('checked', false); // remove all checks if no multi allowed
});

$('.region').on('change', function() {
  let selectedCount = $('.region:checked').length;
  if (!$allowMulti.prop('checked') && selectedCount > 1)
    $(this).prop('checked', false);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
  <label>
    <input type="checkbox" id="allow_multi"> 
    Select multiple regions
  </label>
</p>
<label>
  <input type="checkbox" class="region" value="1"> 1
</label>
<label>
  <input type="checkbox" class="region" value="2"> 2
</label>
<label>
  <input type="checkbox" class="region" value="3"> 3
</label>
<label>
  <input type="checkbox" class="region" value="4"> 4
</label>