32

I am using Select2 within WooCommerce in some of my own custom areas and I am targeting it with some code to add and removes certain classes and it's working fine except for the SelectWoo instances used by WooCommerce themselves do not add the class using el.addClass('has-selection'); in the example provided.

Example code:

(function($) {
     $('select').each(function(e) {
        handleSelectSelections($(this));
    });
})( jQuery );

function handleSelectSelections(select) {
    var el = (select.next('.select2').length) ? jQuery(select.data('select2').$container) : select;

    if (select.val() !== "" && select.val() !== null) {
        el.addClass('has-selection');
    } else {
        el.removeClass('has-selection');
    }
}

Everything works fine, except when it gets to the actual part where it adds the class it doesn't work - no class is added.

Am I missing something here?

Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
Brett
  • 19,449
  • 54
  • 157
  • 290
  • Did you print select.val()? – bigless May 31 '19 at 02:23
  • @bigless Yes, the value is correct. – Brett May 31 '19 at 11:53
  • 3
    What is the result of el? No console error? – romuleald Jun 08 '19 at 07:37
  • Should `handleSelectSelections` trigger on select change, or only once? Cannot help without working example, do you have an online page? – skobaljic Jun 09 '19 at 10:01
  • @romuleald Correct, it just outputs the element as expected. – Brett Jun 09 '19 at 13:11
  • @skobaljic This particular one only runs once. It is online, but you need to register to view it as it is inside WooCommerces "My Account" section, such as editing your address information where you select the Country and State. Did you still want the link? – Brett Jun 09 '19 at 14:28
  • If you cannot see the issue, than you cannot resolve it. – skobaljic Jun 10 '19 at 08:54
  • Retrieving this from the dead, did you manage to get it working? I think you best bet is to hook into a select2 event: https://select2.org/programmatic-control/events – Luuk Skeur Jun 24 '21 at 16:07
  • @LuukSkeur Been awhile but I don't think I ever did and just left it as it wasn't massively important. If I ever need it again I will check out your link. :) – Brett Jun 28 '21 at 23:24

1 Answers1

-1

May be

if (select.val() !== "" && select.val() !== null) {
    **el.className += 'has-selection';**
} else {
    el.removeClass('has-selection');
}