I am using Select2 version 4.0.6. I want to be able to change the order of presentation of the selected items.
I mean that by default Select2 introduces me A, B, C but not A,C,B or B,C,A in the value field.
How can I achieve this?
Can the display order can change more than once (for instance, does the user get to choose the display order, and there are multiple options that they can select at will)? If you only need to change the order one time, I would just set the order before initializing the Select2 widget. But if the order of the data can change after the Select2 widget is initialized, then—assuming you’re not using the AJAX feature—there are two ways I’m aware of to change to order of the items:
-
Method 1—with hard-coded HTML:
- Remove the current
<option>
s from the DOM (or remove the JavaScriptOption
objects from theSelect
object). (Note that you’ll need to store the options, or at least their data, so you can change their order. - Reorder the data.
- Insert new
<option>
s in the new order (or add newOption
objects to theSelect
object). -
Trigger the
change.select2
event to inform the Select2 widget that the options have changed. Note that you will need to ensure the dropdown is closed before you trigger the event, because the displayed options will not redraw while the dropdown is open.
- Remove the current
-
Method 2—with a JavaScript array:
- Change the order of the data to the desired order.
- Destroy the current Select2 widget.
- Re-initialize the Select2 widget with the data in the new order.
Method 2 might result in some display flashing (when the Select2 widget is destroyed it’s likely the browser will display the HTML <select>
in its place; then the Select2 widget will reappear after it is re-initialized).
If you are using the Select2 AJAX feature to load the Select2’s data, then you should arrange to have the back end data source return the data in the desired order. You would need to indicate the desired order in the request, using a custom request parameter that your back end understands.
Note that you would then need to remove any <option>
s that Select2 had already created in the DOM, and that the newly ordered data would not be retrieved until the user types in the search field (which causes the Select2 to request new results from the back end).