繁体   English   中英

使用jquery更改checkbox的checked属性

[英]changing the checked attribute of checkbox using jquery

我必须从另一个复选框控制已检查状态的复选框列表。

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

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

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

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

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

DEMO

你不能像这样使用方法.reload

$(this).removeAttr('checked').reload(); 
                  // returns Uncaught TypeError: Object #<Object> has no method 'reload' 

删除它,它会工作。

的jsfiddle

对所有复选框使用类,您需要在单击某个复选框时更改这些复选框。 喜欢:

<input id="recipe.read" class="toChange" name="recipe.read" type="checkbox" value="1" rel="read" />

我在除第一个复选框之外的所有复选框中添加了一个class =“toChange”。

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

然后使用以下脚本:

$('#readall').click(function(){
    var checkStatus = $(this).is(':checked');   

    if(checkStatus){
        $(".toChange").attr('checked', 'checked');
    }
    else{
        $(".toChange").removeAttr('checked')
    }   
});

演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM