0

I'm using the following code and it does toggle my check boxes, but not correctly.

It has an issue if the check box has been manually set as checked.

The when you run the code it checks the boxes, but then you click it again it only unchecked the ones that weren't previously checked.

$(".all").click(function(e) {
    var checked = !$(this).data('checked');
    $('.trigger').attr('checked', checked);
    $(this).data('checked', checked);
});

I'm using an input type='image' as my element to run the checking from.

<input type="image" class="all" title="All" src="toggle.png"/>

I've tried using the following, but when that runs it unchecks the checkboxes and then removes the image i'm using to call it.

$('.all').toggle(function(){
    $('input:checkbox').attr('checked','checked');

},function(){
    $('input:checkbox').removeAttr('checked');
})

Can anyone advise how I can do this correctly.

Thanks

Tom
  • 1,436
  • 24
  • 50
  • Post a [mcve] in your question please. Use the `<>` icon to add a stacksnippet directly to the question so that we can observe the behavior that you're describing – j08691 Mar 14 '17 at 14:24
  • Use `:checked` against the checkbox rather than a custom data value. Or set/unset your data value in the `.all` code. – freedomn-m Mar 14 '17 at 14:40
  • 1
    An example with the code of the duplicate https://jsfiddle.net/7sm17x1k/ – DaniP Mar 14 '17 at 14:41
  • Thanks the example made sense and I've now go this working. – Tom Mar 14 '17 at 15:42

1 Answers1

0

If you want to toggle you have to select based on 'checked' attribute:

    $('.all').click(function(){

    var checked = $('input:checkbox').not(':checked');
    $('input:checkbox:checked').removeAttr('checked');
    checked.attr('checked','checked');
  });

I'm a bit confused with this bit 'only unchecked the ones that weren't previously checked' - what do you mean, something that was not checked cannot be unchecked.

Here is a working fiddle: https://jsfiddle.net/4ckjwv8b/

Btw. if you just want to always select one option you could use input type 'radio'.

Martina
  • 739
  • 3
  • 13
  • this doesn't seem to work for me. When I use toggle it hide the image I'm using to trigger the toggle. – Tom Mar 14 '17 at 15:42
  • I have updated my answer, use click instead of toggle and also 'checked' needs to be stored in a variable otherwise it will be unchecked on next line and it will get selected. – Martina Mar 14 '17 at 18:02