javascript 如果选中一个则禁用所有复选框并在未选中时启用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11365491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Disable all checkboxes if one selected and enable when none selected
提问by user1410668
Im' writing a basic script and I can't seem to understand why it is not working. Basically, the script locks all the checkboxes if one is selected and then unlocks them if the user decides to deselect the checkbox.
我正在编写一个基本脚本,但我似乎无法理解为什么它不起作用。基本上,脚本会在选中一个复选框时锁定所有复选框,然后在用户决定取消选中复选框时将其解锁。
Here is the code
这是代码
//Script for questions where you check one option or the other (locks other options out)
$('.optionBox input').click(function(){
var optionBoxElement$ = $(this).closest('.optionBox');
//If no option is checked, the make all the options available to be selected
//Otherwise, one option must be checked so lock out all other options
if(optionBoxElement.find('input:not(:checked)').length == optionBoxElement.find(':input').length)
optionBoxElement.find(':input').prop('disabled',false);
else
optionBoxElement.find('input:not(:checked)').prop('disabled',true);
optionBoxElement.find('input:checked').prop('disabled',false); //makes sure that the checkbox that was checked is not disabled so the user can uncheck and change his answer
});
回答by ?????
You can do it like below. All you have to do is check if the checkbox is checked.
你可以像下面那样做。您所要做的就是检查复选框是否被选中。
$('.optionBox input:checkbox').click(function(){
var $inputs = $('.optionBox input:checkbox');
if($(this).is(':checked')){ // <-- check if clicked box is currently checked
$inputs.not(this).prop('disabled',true); // <-- disable all but checked checkbox
}else{ //<-- if checkbox was unchecked
$inputs.prop('disabled',false); // <-- enable all checkboxes
}
})
回答by Kyeotic
Something like this fiddle:
像这样的小提琴:
//Script for questions where you check one option or the other (locks other options out)
$(':checkbox').click(function(){
var $checkbox = $(this);
var isChecked = $checkbox.is(':checked')
//If no option is checked, the make all the options available to be selected
//Otherwise, one option must be checked so lock out all other options
if(isChecked)
$checkbox.siblings(":checkbox").attr("disabled", "disabled");
else
$checkbox.siblings(":checkbox").removeAttr("disabled");
});?
回答by Scott Sauyet
Something like this fiddle, perhaps.
也许像这个小提琴这样的东西。
$('.optionBox :checkbox').click(function() {
var $checkbox = $(this), checked = $checkbox.is(':checked');
$checkbox.closest('.optionBox').find(':checkbox').prop('disabled', checked);
$checkbox.prop('disabled', false);
});