【问题标题】:Disable other checkboxes if two of them are selected using jquery如果使用 jquery 选择了其中两个复选框,则禁用其他复选框
【发布时间】:2026-01-11 07:05:01
【问题描述】:
我有以下 4 个复选框。
<input type="checkbox" id="41" name="4[]" value="abc" style="width:10px"></td>
<input type="checkbox" id="42" name="4[]" value="qwe" style="width:10px"></td>
<input type="checkbox" id="43" name="4[]" value="xyz" style="width:10px"></td>
<input type="checkbox" id="44" name="4[]" value="pqr" style="width:10px"></td>
如果我选择其中两个复选框,我需要一种方法来禁用其他复选框。
任何帮助将不胜感激。
【问题讨论】:
标签:
javascript
php
jquery
checkbox
【解决方案1】:
你可以使用:
$(":checkbox[name='4[]']").change(function(){
if ($(":checkbox[name='4[]']:checked").length == 2)
$(':checkbox:not(:checked)').prop('disabled', true);
else
$(':checkbox:not(:checked)').prop('disabled', false);
});
Working Demo
【解决方案2】:
试试这个
$('input:checkbox').on('change', function(evt) {
if($(this).siblings(':checked').length >= 2) {
this.checked = false;
console.log(this.value)
}
});
DEMO
【解决方案3】:
试试这个。
Javascript
$('input[type=checkbox]').change(function(){
if($(this).is(':checked')){
$('input[type=checkbox]').attr('disabled',true);
$(this).attr('disabled','');
}
else{
$('input[type=checkbox]').attr('disabled','');
}
});
HTML
1 <input type="checkbox" name="finallevelusers[]" value="1"/>
2 <input type="checkbox" name="finallevelusers[]" value="1"/>
3 <input type="checkbox" name="finallevelusers[]" value="1"/>
4 <input type="checkbox" name="finallevelusers[]" value="1"/>
Demo
【解决方案4】:
首先开始为每个复选框添加唯一的 id。
然后你可以附加函数来改变这样的事件:
$("input[type=checkbox]").change(function() {
...
});
然后简单地计算 :checked items 和瞧:
var n = $("input:checked").length;
我想你可以自己做。
【解决方案5】:
Demo Fiddle
$('[type="checkbox"]').change(function(){
if(this.checked && $(':checked').length == 2){
$('[type="checkbox"]').not(':checked').prop('disabled',true);
}
});
为您的元素使用唯一的 Id 属性。
如果没有通用属性,则使用通用选择器的通用类名,如$('[type="checkbox"]')
$(':checked').length 和 :checked 伪让您只查找选中的输入。
.prop('disabled',true); 用于禁用输入 - 请参阅 .prop()。