复选框选择/取消选择触发器首次使用但在后续尝试时失败

时间:2016-04-18 10:55:03

标签: javascript jquery checkbox html5-data

我有一大堆基于html data- *标签的jQuery,可以通过组中的复选框来处理搜索表单。

单击“全部”复选框,其他所有复选框都应取消选中(每次都可以正常工作)。

现在,如果选中“全部”并单击其他选项,则“全部”应该取消选中,这也可以按预期工作。

但是,如果您愿意,可以取消选中“全部”复选框,然后默认选中其余的复选框,以便取消选择所需的结果。

如果到目前为止你没有改变任何其他人,这是第一次有效,但是如果选择了任何其他复选框栏“全部”,或者如果你选择了那么你已经点击了“全部”按钮再次取消选择。

任何有关它的内容的想法都会受到高度赞赏(我已经尝试使用控制台来发现它没有做什么,但到目前为止它没有提供任何线索)。

以下示例。

html...
<input data-sel-group='group1' id='group1_all'/>
<input data-sel-group='group1' id='group1_1'/>
<input data-sel-group='group1' id='group1_2'/>
/html...

jQuery...
$('input:checkbox').on('click',function(){
var sel = $(this).data('sel-group'),
    all = $('#'+sel+'_all'),
    chk = all.is(':checked');
    if($(this).attr('id')==all.attr('id')){
        if(chk){
            $('input[data-sel-group="'+sel+'"][id!="'+sel+'_all"]').attr('checked', false);
        }else{
            $('input[id!="'+sel+'_all"][data-sel-group="'+sel+'"]').attr('checked', true);
        }
    }else{
        all.attr('checked', false);
        if($('input[data-sel-group="'+sel+'"]:checked').length<=0){
            all.attr('checked', true);
        }
    }
})

2 个答案:

答案 0 :(得分:1)

使用.prop()代替.attr()

$(selector).prop('checked', true/false);

同时浏览.prop() vs .attr()

答案 1 :(得分:0)

在设置复选框属性时,应使用延迟执行。 Please refer this blog

相关问题