Add a class to an element depending on the selected options in select2 jQuery
Solution 1:
I made a couple of changes to your code and got it to work. First of all, I like to bind handlers to DOM objects with .on()
method. In my experience this works better than the shorthands, like click()
etc.
Second, since you don't have (at least in the snippet) other elements with class sf-status
except the <li>
, you can shorten the jQuery selector to $('.sf-status')
. Ofcourse you can also use ID if you have others. Anyhow, the code below should work:
$('.sf-type select').on('change',function () {
var val = $(this).val();
if (val === 'item4') {
$('.sf-status').addClass('active');
}
});
This does work with the original $('.searchandfilter').find('.sf-status').addClass('active');
also.