复选框不再检查,如果使用Jquery的切换功能

Checkbox no longer checks if used with Jquery Toggle function?

本文关键字:Jquery 功能 不再 再检查 如果 复选框      更新时间:2023-09-26

我有一个复选框,如果选中,应该启用下面的一些单选按钮。

如果复选框未选中,则下面的单选按钮禁用,如果它们本身已选中,则变为未选中。

为了做到这一点,我使用了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 Version: 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>

尝试使用。change()代替toggle()

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

演示:小提琴

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

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