Difference between triggering change() and select() events

Hello,
I need to add (and select) a new option to a select element via Javascript.
The element can be a standard select, a select2 or an “ajax” select2.

I am using this code and everything works as expected:


var option = document.createElement(“option”);
option.text = field_display_value;
option.value = field_value;
select_element.add(option);
select_element.value = field_value;
$(‘select[name="’+field_name+’"]’).trigger(‘change’);

However, from here https://select2.org/programmatic-control/add-select-clear-items it seems that the correct event to fire is select(), at least for ajax select2.
Am I missing something if I use change()?

I think that select() allows me to access additional properties of the item coming from the ajax call (other than the “field_value” or “field_display_value”) but if I don’t need them there should be no difference. Am I right or there is something behind the scenes that wouldn’t work as expected?

Thanks!

You seem to be doing it correctly, and you said your code works. FWIW, I searched the documentation page you linked to, but the text trigger('select') does not appear anywhere. So I’m not sure where that idea came from, but I don’t see it on the documentation page.

Thanks for the reply John. You will see the code I am referring to if you search this comment:
“manually trigger the select2:select event”

I think the only reason you’d need to fire the select2:select event is if you need to pass additional data beyond what’s represented in the Option element you created and added to the select. Since an HTML option element can only contain an “id” and “value” property (as well as innerText if you choose to set that), if you need to include additional data in the internal data structure, then triggering select2:select does allow you to pass the params property that contains the full data object.

That’s what I thought, thanks!