取消选中 Bootstrap 复选框按钮 - 纯 JavaScript

4

我的应用程序有一个数据筛选功能,用户可以使用复选框和下拉菜单来选择他们想要的数据筛选方式

我正在使用Bootstrap复选框:

<div class="btn-group" data-toggle="buttons">
 <label class="btn btn-primary active">
  <input type="checkbox" autocomplete="off" checked> Checkbox 1 (pre-checked)
 </label>
 <label class="btn btn-primary">
  <input type="checkbox" autocomplete="off"> Checkbox 2
 </label>
 <label class="btn btn-primary">
  <input type="checkbox" autocomplete="off"> Checkbox 3
 </label>
</div>

我有一个“清除筛选器”按钮,可以清除所有用户在筛选器中输入的内容,重置所有复选框、下拉列表和文本字段。

我可以像这样重置下拉列表:

// sectorPicker is drop down
document.getElementById('sectorPicker').reset();

以下是我的复选框的图片: enter image description here 但我不知道如何将屏幕上的Bootstrap复选框重置为取消所有复选框。
有什么想法吗?
4个回答

9

这将会移除选中状态属性和其父标签中的激活类(active class)。

$(":checkbox").prop('checked', false).parent().removeClass('active');

3
尝试这个,它将循环遍历所有选中的复选框并使其不被选中。或者您可以给每个复选框添加一个类属性,然后循环遍历它们。
     $( "input:checked" ).each(function(){
           $(this).removeAttr("checked");
           $(this).parent().removeClass("btn btn-primary");
            $(this).parent().removeClass('active');
           $(this).parent().addClass("btn btn-default");
     });

//方式二:

<div class="btn-group" data-toggle="buttons">
 <label class="btn btn-primary active">
  <input type="checkbox" class="mychk" autocomplete="off" checked> Checkbox 1 (pre-checked)
 </label>
 <label class="btn btn-primary">
  <input type="checkbox" class="mychk" autocomplete="off"> Checkbox 2
 </label>
 <label class="btn btn-primary">
  <input type="checkbox" class="mychk" autocomplete="off"> Checkbox 3
 </label>
</div>

$(".mychk").each(function(){
 $(this).removeAttr("checked");
});

谢谢你的回答。我尝试了这个方法,但我的复选框仍然保持高亮状态。如果你查看我的问题,我已经发布了一张图片。你可以看到即使清除了它们,它们仍然是蓝色高亮的。 - Skywalker
那是你的按钮类,你需要从标签元素中删除btn btn-primary类,看看我的更新答案。 - Mahesh

2
据我所知,Bootstrap 复选框使用属性而不是属性。类似这样的代码 $("[type='checkbox']").prop("checked", false) 应该可行。

1
$('#You_id_checkbox').removeAttr("checked");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接