【问题标题】:How to uncheck a single radio button if disabled by another radio?如果被另一个收音机禁用,如何取消选中单个单选按钮?
【发布时间】:2011-12-27 20:43:35
【问题描述】:

jQuery 新手,在这里。我不能让它工作。这是我用来禁用基于前一个单选按钮的单选按钮的方法。

$('document').ready(function() {
    $('input[name="a"]').change(function() {
        if($(this).val() == '1') {
            $('input[name="b"]').removeAttr('disabled');
        } else {
            $('input[name="b"][value="1"]').attr('disabled','disabled');
        }
    });
});

和:

<input type="radio" name="a" value="1" /> A-1
<input type="radio" name="a" value="2" /> A-2

<input type="radio" name="b" value="1" /> B-1
<input type="radio" name="b" value="2" /> B-2

所以如果我检查 A-2,B-1 就会被禁用。但是假设我一开始就检查了 B-1,然后我检查了 A-2,然后我希望 B-1 不被检查。我已尝试将其添加到:

if($('input[name="b"][value="1"]').is(':disabled')) {
    $('input[name="b"][value="1"]').removeAttr('checked');
}

它完成了这项工作,但如果我先检查了 B-2,它也会取消选中它。我只希望 B-1 不受检查。 (我希望这是有道理的。)

我做错了什么?

【问题讨论】:

  • 如果选择了另一个单选,您总是希望取消选中之前选中的单选按钮?

标签: jquery radio


【解决方案1】:
$('input[name="a"]').change(function () {
    var $b = $('input[name="b"]');
    if (this.value == 1) {
        $b.removeAttr('disabled');
    }
    else {
        $('input[name="b"][value="1"]:checked').removeAttr('checked');  // the selector behavior is funky here...
        $b.attr('disabled', true);
    }
});

这可以随心所欲。

你的 [value="1"] 选择器有问题(当使用没有 :checked 时),闻起来像 jquery 错误。不过不用担心;)

a little fiddle for you^^

【讨论】:

    【解决方案2】:

    过去我不得不匆忙学习类似的东西:诀窍是制作一系列单选按钮:

    family NAME
      child ID0
      child ID1
      child IDn
    

    在您的特定情况下,您可能正在寻找这样的东西(性别):

    <input type="radio" name="gender" id='male' value="M" > Male
    <input type="radio" name="gender" id='female' value"F" > Female
    

    例如,喜欢:

    <input type="radio" name="likes" id='tv' value="TV" > Watchs TV
    <input type="radio" name="likes" id='radio' value="radio" > Listens to Radio
    

    当您有一系列单选按钮时,一旦单击一个,另一个将自动取消单击。

    然后你可以检查一下

    $('#male').is(':checked') .... $('#female').is(':checked') .....
    

    而且,您还可以通过单击以下命令来禁用或禁用其中的任何一个或禁用另一个:$('#male').click();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-22
      • 2011-11-05
      • 2018-02-05
      • 2015-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多