【问题标题】:Disable all checkboxes if one selected and enable when none selected如果选中一个则禁用所有复选框,并在未选中时启用
【发布时间】:2012-07-06 15:46:10
【问题描述】:

我正在编写一个基本脚本,但我似乎无法理解为什么它不起作用。基本上,如果选中一个复选框,脚本会锁定所有复选框,然后如果用户决定取消选中复选框,则将其解锁。

这里是代码

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

});

【问题讨论】:

  • 第一个问题:为什么不使用单选按钮?
  • 不适合我的应用程序。我只想要一个针对这种情况的通用脚本。
  • 尝试添加HTML,看看是否有错误
  • 太糟糕了,它给了我$inputs.prop is not a function我切换到js(链接)[stackoverflow.com/questions/6060681/…

标签: javascript jquery html


【解决方案1】:

你可以像下面那样做。您所要做的就是检查复选框是否被选中。

$('.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
    }
})

http://jsfiddle.net/ZB8pT/

【讨论】:

  • 这将影响页面上每个 .optionBox 中的每个复选框。这可能没问题,但也可能不是我们想要的。
【解决方案2】:

类似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"); 

});​

【讨论】:

  • 我不确定其他复选框是给定复选框的简单兄弟。
  • 很公平,但这是一个例子。我怀疑他是否希望禁用所有其他复选框,如果它们是分组的兄弟姐妹是有道理的。它很容易更改为任何其他选择器,而不会丢失功能。
【解决方案3】:

也许是this fiddle

$('.optionBox :checkbox').click(function() {
    var $checkbox = $(this), checked = $checkbox.is(':checked');
    $checkbox.closest('.optionBox').find(':checkbox').prop('disabled', checked);
    $checkbox.prop('disabled', false);
});

【讨论】:

    猜你喜欢
    • 2014-01-08
    • 1970-01-01
    • 1970-01-01
    • 2017-09-08
    • 2019-03-22
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    • 2011-08-28
    相关资源
    最近更新 更多