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!