0

I have the below JQuery code on a Rails 5 app. Works fine if I check the box the first time. Also works fine if I uncheck the same checkbox. But when I reclick the same box I initially clicked, it no longer checks off the box. Anything I'm missing in my code below?

$(".filter-wrapper-f").click(function(){
    var $checkbox = $(this).children(".checkpic");
    if ($checkbox.attr('checked')){
        $checkbox.removeAttr('checked');
    } else {
        $checkbox.attr('checked', true);
    }
});

I've also tried this and it won't work to start with.

$(".filter-wrapper-f").click(function(){
var $checkbox = $(this).children(".checkpic");
    if ($checkbox.prop('checked', true)){
        $checkbox.removeProp('checked');
    } else {
        $checkbox.prop('checked', true);
    }
});
dgreen22
  • 388
  • 4
  • 19
  • 1
    use `prop()` like `$checkbox.prop('checked', true);` – guradio Jan 29 '18 at 03:31
  • 1
    change `attr` to `prop` - either `$checkbox.prop('checked', false)` or `$checkbox.prop('checked', true)` – Ben Kolya Mansley Jan 29 '18 at 03:32
  • @BenKolyaMansley @guradio I tried both but now the initial function doesn't even check the box in the first place. ` var $checkbox = $(this).children(".checkpic"); if ($checkbox.prop('checked', true)){ $checkbox.removeProp('checked'); } else { $checkbox.prop('checked', true); } });` – dgreen22 Jan 29 '18 at 05:15
  • Replace removeProp with `prop('checked',false);` – Ben Kolya Mansley Jan 29 '18 at 12:00

1 Answers1

1

As per the jQuery docs, prop should be used to set the checked attribute.

$checkbox.prop('checked', true)

Explanation here: https://stackoverflow.com/a/5876747/5551783

dgreen22
  • 388
  • 4
  • 19
jake2389
  • 1,166
  • 8
  • 22