0

I've got a chunk of jQuery that works based off html data-* tags to work through checkboxes in a group for a search form.

Click on the 'All' check box and all of the rest of them should become unselected (this works everytime without issue).

Now, if the 'All' is selected and you click a different option then the 'All' should become unselected, this too works as intended.

However if you want to you can unselect the 'All' checkbox which should then default to having the rest of the checkboxes selected so you can unselect your desired results.

If you haven't changed any others so far, this works for the first time but if any other checkbox bar 'All' is selected or if you've already clicked the 'All' button once it fails if you selected then deselect it again.

<input data-sel-group='group1' id='group1_all'/>
<input data-sel-group='group1' id='group1_1'/>
<input data-sel-group='group1' id='group1_2'/>
$('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);
        }
    }
})
TylerH
  • 20,799
  • 66
  • 75
  • 101

2 Answers2

1

Use .prop() instead of .attr()

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

Also go through .prop() vs .attr()

Community
  • 1
  • 1
Satpal
  • 132,252
  • 13
  • 159
  • 168
-1

you should use delayed execution while setting checkbox attribute checked. Please refer this blog