As with many open source projects, the documentation for the Select2 JavaScript plugin is pretty terrible. I always have a tough time finding what I need, so this morning I decided to let ChatGPT help me instead. Here was my prompt:
I am using the Select2 JavaScript package for my project, and I have a select element hooked up so that it returns dynamic options using the ajax callback. I would like for the list of options that are shown to the user to be long form text (example: "[1234] My Project Name"), but when the user selects an option, I only want the ID to appear (example: "[1234]"). Is this possible?
It returned the exact magic I needed, which I've pasted below. Incredible!
Response I Received
Yes, this is possible with Select2 by customizing how the options are rendered and how the selected value is displayed. Specifically, you'll use:
templateResult
to control how items appear in the dropdown.templateSelection
to control how the selected item is displayed.- Ensure that the underlying
id
is the short text (e.g.,[1234]
), and thetext
can be long form ([1234] My Project Name
).
Example Code:
$('#your-select').select2({
ajax: {
url: '/your/data/source',
dataType: 'json',
processResults: function (data) {
return {
results: data.map(function (item) {
return {
id: `[${item.id}]`, // What gets submitted/stored
text: `[${item.id}] ${item.name}` // What shows in dropdown
};
})
};
}
},
templateResult: function (data) {
return data.text; // Full label in the dropdown
},
templateSelection: function (data) {
return data.id; // Just the ID when selected
},
escapeMarkup: function (markup) { return markup; } // Optional, if using HTML
});