Having trouble working with SelectWoo instances of Select2 within WooCommerce
Asked Answered
G

1

38

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?

Godbeare answered 30/5, 2019 at 22:25 Comment(9)
Did you print select.val()?Landgravine
@Landgravine Yes, the value is correct.Godbeare
What is the result of el? No console error?Radii
Should handleSelectSelections trigger on select change, or only once? Cannot help without working example, do you have an online page?Elisaelisabet
@Radii Correct, it just outputs the element as expected.Godbeare
@Elisaelisabet 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?Godbeare
If you cannot see the issue, than you cannot resolve it.Elisaelisabet
Retrieving this from the dead, did you manage to get it working? I think you best bet is to hook into a select2 event: select2.org/programmatic-control/eventsHarquebus
@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. :)Godbeare
C
0

May be

if (select.val() !== "" && select.val() !== null) {
    **el.className += 'has-selection';**
} else {
    el.removeClass('has-selection');
}
Carew answered 12/8, 2022 at 7:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.