0

I want to target the .sf-input-checkbox class in this instance. But my (this) is attached to the .searchandfilter instead.

$(document).on("sf:ajaxfinish", ".searchandfilter", function(){
    if ( $('.sf-input-checkbox').is(":checked") ) {
    $(this).addClass('jordanchecked');
}
});

Result currently:

<div class="searchandfilter jordanchecked">
    <input type="checkbox" class="sf-input-checkbox">
</div>

I am after this:

<div class="searchandfilter">
    <input type="checkbox" class="sf-input-checkbox jordanchecked">
</div>
wharfdale
  • 1,148
  • 6
  • 23
  • 53
  • 3
    So target the checkbox, the same way you did in the if conditional. if statements don't change what `this` is. – Kevin B Aug 19 '19 at 21:51
  • Possible duplicate of [How to get the children of the $(this) selector?](https://stackoverflow.com/questions/306583/how-to-get-the-children-of-the-this-selector) – Phil Aug 19 '19 at 21:52
  • `this` doesn't change in an `if` statement. You'll have to use a class selector. Or you could assign the selector to a variable outside the statement and use the variable inside the statement. Like: `$this = $('.example'); if ($this.is()) { $this.addClass(); }` – Studocwho Aug 19 '19 at 21:55

1 Answers1

1

The problem is you have no relational link in your JS between the this of the event handler and the checkbox. That missing relationship is parent-child.

$(document).on("sf:ajaxfinish", ".searchandfilter", function(){
    let cb = $(this).children('.sf-input-checkbox');
    if (cb.is(":checked")) cb.addClass('jordanchecked');
});
Mitya
  • 33,629
  • 9
  • 60
  • 107