javascript - 使用 jquery 更改复选框的选中属性

标签 javascript jquery html checkbox checkboxlist

我必须控制另一个复选框的复选框列表的选中状态。

HTML:

    <input id="readall" name="readall" type="checkbox" value="1">
<div id="permGrid">
    <input id="recipe.read" name="recipe.read" type="checkbox" value="1" rel="read">
    <input id="group.read" name="group.read" type="checkbox" value="1" rel="read">
    <input id="ingredients.read" name="ingredients.read" type="checkbox" value="1" rel="read">
</div>

JS:

$('#readall').click(function()
{
    var checkStatus = $(this).is(':checked');
    var checkboxList =  $('#permGrid input[rel="read"]');
    $(checkboxList).attr('rel', 'read').each(function(index)
    {
        if(checkStatus == true)
        {
            $(this).attr('checked', 'checked');
            console.log($(this).attr('checked'));
        }
        else
        {
            $(this).removeAttr('checked').reload();
            console.log($(this).attr('checked'));
        }
    });
});

上面的代码看起来不错,但检查/取消检查仅在第一次有效。但是,当我第二次单击主复选框时,它不会将其他复选框的状态更改为“已选中”。有什么需要我做的吗?

我发现了类似的东西 here 。我比较了代码和我的代码,这个代码有点相似,但我的代码不起作用。

最佳答案

尝试使用 prop,并像这样缩短代码

$('#readall').click(function () {
    var checkboxList = $('#permGrid input[rel="read"]')
    checkboxList.prop('checked', this.checked);
});

DEMO

关于javascript - 使用 jquery 更改复选框的选中属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22347095/

相关文章:

javascript - 使用JS将输入设置为只读

html - 内容大于 div 本身的 iframe 样式 div

Jquery Append On click函数表

javascript - Node.js Web 应用程序浏览器兼容性

php - 检查用户是否从不同域登录

javascript - 从异步函数获取 e.target 值的问题

javascript - 我如何调整 Div 幻灯片 jquery

jquery - 如何知道所有 AJAX 调用何时完成?

javascript - 如何为 CSS 计算圆的 x 和 y

javascript - 如何遍历这个javascript对象