Is it possible to specify abbreviations for items in my lists, which can also be searched?


#1

I just discovered Select2, and it looks amazing.

Let’s say I have a standard list of country names. If I have “United States” listed but someone types in “US” or “USA”, that’s not going to show them the “United States” item that they’re looking for. Is there a way to set “alternative” values that can be used to make list searching a bit less rigid? (I know they would also probably see other results when they type “US”, but seeing 3-4 options is better than seeing ~200.)

If this isn’t possible yet, it’d be great if this could be added to the “suggestions” list.
Maybe it’d be something like:
<option value="United States" data-select2="US,USA,America">United States</option>

Thanks for your help!


#2

Yes, this is possible. In fact I have written some code that does it. The two main features you need are:

  1. the “extra data” in the Select2 data structure (this is where you’ll store the abbreviation for each item}, and
  2. a custom matcher function that matches the user’s input against both the item’s text and its abbreviation.

You can see my example code here: https://codepen.io/John30013/project/editor/Abdgnk

Note that my example code auto-generates the abbreviations from the item text, but that’s just for demonstration purposes.