如何使用jquery防止用户取消一组复选框输入中的所有复选

How to prevent user from uncheck all checks from a group of checkboxes inputs with jquery

本文关键字:输入 复选框 一组 jquery 何使用 用户 取消      更新时间:2023-09-26

你好,我正在使用一组复选框来过滤feed中的数据,基本上我将所有复选框默认设置为活动,我如何防止用户取消勾选所有选项?我至少要检查一个。希望有人能帮忙。

我创建了一个jsfiddle

这是我的html:
<div class="pull-left" id="filter">
    <div class="btn-group" data-toggle="buttons">
        <label class="btn btn-primary active" id="btnOne">
            <input type="checkbox" name="filter"> One Selected
        </label>
        <label class="btn btn-primary active" id="btnTwo">
            <input type="checkbox" name="filter"> Two Selected
        </label>
        <label class="btn btn-primary active" id="btnThree">
            <input type="checkbox" name="filter"> Three Selected
        </label>
        <label class="btn btn-primary active" id="btnFour">
            <input type="checkbox" name="filter"> Four Selected
        </label>
    </div>
</div>

将此代码添加到javascript, JSFiddle

$(function() {
  $(".btn.active").click(function(){
      if($(this).hasClass('active')){
          if($(".btn.active").length===1){
              return false;     
          }
    }
  });
});

注意,你没有改变复选框的checked属性,你使用的是带有active类切换行为的按钮。

最好是用radio buttons代替checkboxes

我发现更改事件更可靠,我会阻止用户取消选中所有复选框,如下所示:

$(':checkbox[name=filter]').on('change', function() {
    $(':checkbox[name=filter]:checked').length == 0 
    && !this.checked 
    && $(this).prop('checked', true);
});

$(function() {
    $(':checkbox[name=filter]').on('change', function() {
        $(':checkbox[name=filter]:checked').length == 0 && !this.checked && $(this).prop('checked', true);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pull-left" id="filter">
    <div class="btn-group" data-toggle="buttons">
        <label class="btn btn-primary active" id="btnOne">
            <input type="checkbox" name="filter"> One Selected
        </label>
        <label class="btn btn-primary active" id="btnTwo">
            <input type="checkbox" name="filter"> Two Selected
        </label>
        <label class="btn btn-primary active" id="btnThree">
            <input type="checkbox" name="filter"> Three Selected
        </label>
        <label class="btn btn-primary active" id="btnFour">
            <input type="checkbox" name="filter"> Four Selected
        </label>
    </div>
</div>