问题
I am having below 4 checkboxes.
<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>
I need a way to disabled other checkboxes if I select two of them.
Any help would be much appreciated.
回答1:
You can use:
$(":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:
Try this
$('input:checkbox').on('change', function(evt) {
if($(this).siblings(':checked').length >= 2) {
this.checked = false;
console.log(this.value)
}
});
DEMO
回答3:
Try This.
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:
First of all start to add unique id to each checkbox. Then you can attach function to change event such like that:
$("input[type=checkbox]").change(function() {
...
});
then simply count :checked items and voila:
var n = $("input:checked").length;
rest you can do on your own i suppose.
回答5:
Demo Fiddle
$('[type="checkbox"]').change(function(){
if(this.checked && $(':checked').length == 2){
$('[type="checkbox"]').not(':checked').prop('disabled',true);
}
});
Use unique Id attributes for your elements.
If there is no common attribute, use a common class name of a generic selector like
$('[type="checkbox"]')
$(':checked').length
with:checked
pseudo lets you find only checked inputs..prop('disabled',true);
is used to disable the inputs - Refer .prop().
来源:https://stackoverflow.com/questions/24240621/disable-other-checkboxes-if-two-of-them-are-selected-using-jquery