When using Select2 v4, the suggested (actually the right) way to set a selected value programmatically, is to manipulate the underlying select element, add the desired <option>
elements you want, set the value with $selectElement.val(<value>)
and trigger a .trigger('change')
event so that select2 plugin will update itself from the underlying select element. You can see this here.
The problem with this is when you have defined a templateSelection
, that returns not just text for the selected value, but a whole HTML DOM (for instance, you may apply styling, add images, icons etc etc and return that as the rendered selection).
templateSelection
accepts input as it comes from either an array datasource, or an ajax datasource etc. Each item represents one option but it may have more than just and id
and a text
. templateSelection
may take into account many of the item's properties to produce the rendered output.
You can only define value and text in an <option>
element. You cannot define the actual object (item) you want to set as selected, so that the templateSelection
may produce the right output.
Is there a way to achieve that using only select2's API?
If not, is there any other workaround to have the value selected from code rendered correctly through templateSelection
?