禁用所有复选框(如果选中),并在未选中时启用

use*_*668 2 html javascript jquery

我正在写一个基本的脚本,我似乎无法理解为什么它不起作用.基本上,如果选中了一个复选框,脚本将锁定所有复选框,如果用户决定取消选中该复选框,则会解锁它们.

这是代码

//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    

});
Run Code Online (Sandbox Code Playgroud)

ᾠῗᵲ*_*ᵲᄐᶌ 5

你可以像下面这样做.您所要做的就是检查复选框是否已选中.

$('.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
    }
})
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/ZB8pT/