Javascript 如何防止用户使用jquery取消选中一组复选框输入中的所有复选框
您好,我正在使用一组复选框来过滤提要中的数据,基本上我将所有复选框设置为默认活动,如何防止用户取消选中所有选项?我至少需要检查一个。希望有人能帮忙 我创造了一个 这是我的html:Javascript 如何防止用户使用jquery取消选中一组复选框输入中的所有复选框,javascript,jquery,html,twitter-bootstrap,twitter-bootstrap-3,Javascript,Jquery,Html,Twitter Bootstrap,Twitter Bootstrap 3,您好,我正在使用一组复选框来过滤提要中的数据,基本上我将所有复选框设置为默认活动,如何防止用户取消选中所有选项?我至少需要检查一个。希望有人能帮忙 我创造了一个 这是我的html: <div class="pull-left" id="filter"> <div class="btn-group" data-toggle="buttons"> <label class="btn btn-primary active" id="btnOne"
<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
请注意,您没有更改复选框
checked
属性,而是使用带有启动的活动的类切换行为的按钮 最好的选择是使用单选按钮
而不是复选框
我发现更改事件更可靠,我会防止用户取消选中所有复选框,如:
$(':checkbox[name=filter]').on('change', function() {
$(':checkbox[name=filter]:checked').length == 0
&& !this.checked
&& $(this).prop('checked', true);
});
$(函数(){
$(':复选框[name=filter]')。在('change',function()上{
$(':checkbox[name=filter]:checked')。长度==0&&!this.checked&&$(this.prop('checked',true);
});
});代码>
选定的一个
选择两个
选定三个
四人入选
不确定,因为您使用的是bootstrap(没有使用它的经验)-是否在加载时自动选中复选框,或者只是按钮有“活动”类?只有按钮有“活动”类,我认为最好检查一下,比如最后一项是否有活动类。。防止点击?
$(':checkbox[name=filter]').on('change', function() {
$(':checkbox[name=filter]:checked').length == 0
&& !this.checked
&& $(this).prop('checked', true);
});