wharfdale
wharfdale

Reputation: 752

Attach (this) to secondary jquery element

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>

Upvotes: 0

Views: 37

Answers (1)

Mitya
Mitya

Reputation: 34556

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');
});

Upvotes: 1

Related Questions