复选框不再检查是否与Jquery Toggle功能一起使用?

时间:2014-03-23 11:45:45

标签: javascript jquery checkbox toggle

我有一个复选框,如果选中,则应在其下方启用一些单选按钮。

如果取消选中该复选框,则会禁用下面的单选按钮,如果选中它们,则取消选中。

要做到这一点,我使用了切换功能:

$( "#mycheckbox" ).toggle(function() {
    $('#radiobuttons input').attr('disabled', false);
}, function() {
    $('#radiobuttons input').attr('disabled', true);
    $('#radiobuttons input').removeAttr('checked');
});

但是,现在我的复选框正在使用Toggle功能,它本身不会检查。

要解决我尝试过的问题:

$( "#mycheckbox" ).toggle(function() {
    $('#radiobuttons input').attr('disabled', false);
    $("#mycheckbox").attr('checked','checked');
}, function() {
    $('#radiobuttons input').attr('disabled', true);
    $('#radiobuttons input').removeAttr('checked');
    $("#mycheckbox").removeAttr('checked');
});

但这也行不通。

有没有人知道解决这个问题?

小提琴:http://jsfiddle.net/P95xg/3/

Jquery版本:1.4.3

HTML:

<label>
    <input type="checkbox" name="mycheckbox" id="mycheckbox" value="Y" />
    <span><strong> Label text here </strong></span>
</label>

<div id="radiobuttons">
<label class="hit"><input type="radio" name="accommodation" value="Standard Room Cat 1" />
    <span>
        <strong>Standard Room Category 1 </strong>
    </span>
    </label>

    <label class="hit"><input type="radio" name="accommodation" value="Standard Room Cat 2" />
    <span>
        <strong>Standard Room Category 2 </strong>
    </span>
    </label>
</div>

2 个答案:

答案 0 :(得分:1)

尝试使用.change()而不是toggle()

var $radios = $('#radiobuttons input');
$("#mycheckbox").change(function (e) {
    $radios.attr('disabled', !this.checked);
    if(!this.checked){
        $radios.removeAttr('checked');
    }
});

演示:Fiddle

注意:仍然没有找到上述行为的原因

答案 1 :(得分:0)

toggle函数用于显示和隐藏元素。

我的建议是在复选框中添加一个事件处理程序,检查复选框是否已选中,然后启用或禁用单选按钮。

这样的事情:

(function () {
    // Store our radio buttons and checkbox:
    var radioButtons = $('#radiobuttons input'),
        checkbox = $('#checkbox');

    // Add an event handler:
    checkbox.on('change', function () {
        // When our checkbox is checked, the radioButtons become active:
        radioButtons.prop('disabled', !checkbox.prop('checked'));
    });
}());