Cannot rename selected option

Hello everybody !

When renaming a select option, it won’t rename the corresponding selected widget’s label.

For example, in https://select2.org/appearance

I choose alaska.

Then, execute: $(’[value=AK]’).html(‘lolo’)

The option is renamed in the select, but the widget is not updated.

Is this a bug or missing feature ?

Thanks

This isn’t a bug per se, but it’s also not a “supported” feature. However, it can be “hacked”, as long as you only need to rename the selected item(s).

After the Select2 widget is initialized, it maintains an internal data structure separate from the <option> elements in the original <select>. There is no way to access “random” items in the internal data structure, but there is a way to access the selected items(s): $('#your-select-id').select2('data'). This code returns an array of the data object(s) representing the selected item(s) in the widget. Each of these objects has a text property that you can update and then trigger the change event:

    // After the user has selected the item:
    $('#your-select-id').select2('close');  // ensure the dropdown is closed.
    var selectedItem = $('#your-select-id').select2('data')[0];
    selectedItem.text = 'lolo';  // change the text of the selected item in the widget.
    $('#your-select-id').trigger('change'); // update the widget's internal state.
    $('value=[' + selectedItem.id + ']').text('lolo'); // change the text of the <option> in the DOM.

Note that if the dropdown is still open when you execute this code, you won’t see the change in the dropdown until it is closed and reopened. That’s why I included the .select2('close'); call. You also have to update the text of the option element separately, which is what the last line of code does.