【问题标题】:changing the checked attribute of checkbox using jquery使用 jquery 更改复选框的选中属性
【发布时间】:2014-03-12 09:29:34
【问题描述】:

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

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。我比较了代码和我的代码,这段代码有点相似,但我的代码不起作用。

【问题讨论】:

    标签: javascript jquery html checkbox checkboxlist


    【解决方案1】:

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

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

    DEMO

    【讨论】:

      【解决方案2】:

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

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

      删除它,它会起作用。

      JSFiddle

      【讨论】:

        【解决方案3】:

        为所有需要在单击某个复选框时更改的复选框使用一个类。喜欢:

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

        Demo

        【讨论】:

          猜你喜欢
          • 2012-05-26
          • 2013-02-23
          • 1970-01-01
          • 2013-09-09
          • 1970-01-01
          • 2011-04-06
          • 2014-06-16
          • 2012-08-17
          • 1970-01-01
          相关资源
          最近更新 更多