Can't select programmatically

I’m using Select2 version 4 with ACF Pro v5.7.12

After the form loads fully - and the Select2 fields are fully populated - I run this code:

$('#s2id_acf-field_58b7183e6cd9b').val( "Greek" );
$('#s2id_acf-field_58b7183e6cd9b').trigger('change');

But unfortunately it doesn’t select GREEK - instead nothing happens. There are no console error messages either.

I’ve also tried this unsuccessfully:

$('#s2id_acf-field_58b7183e6cd9b-input').val( "Greek );
$('#s2id_acf-field_58b7183e6cd9b-input').trigger('change');

Likewise I can’t trigger any change function

$('#s2id_acf-field_58b7183e6cd9b-input').on('change', function() {
	console.log ( "change happened" );
});

It seems like the Select2 fields are just dead fish and floating there without doing a thing.

Is “Greek” the value (i.e., the item.id value) of the option you’re trying to select, or is it the option’s text?

Is it possible for you to post your code on JSFiddle or Codepen.io?

Thanks - it’s both - the value and the text.

(Sorry, I’m not familiar with JSFiddle or Codepen - I’ll take a look at them.)

Yeah, your first code example should work. It seems like perhaps the Select2 isn’t actually initializing. Do you see the rendered widget? Does the dropdown and the search box work?

Have you checked the JavaScript console for any error messages?

This is why I’d like to see the full code in a “working” example, so I could perform some additional troubleshooting that I can’t really do without that.

Thanks for your help - in the end I got it working; it seems ACF had changed the way the selector is identified.

1 Like