Select2 for Codes
by Bruno G.
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.full.min.js"></script>
<select class="selectMe" id="select1" data-init="Option 5"></select><br>
<select class="selectMe" id="select2" data-init="Option 4"></select><br>
<select class="selectMe" id="select3" data-init="Option 2"></select><br>
<select class="selectMe" id="select4" data-init="Option 7"></select><br>
CSS
.select2-dropdown .select2-results::after {
content: "To select: Click or Arrows + Enter";
content: "Pour sélectionner : Cliquer ou Flèches + Entrée";
text-align: center;
display: block;
margin-top: 3px;
background-color: antiquewhite;
}
JavaScript
const items = [
{id: '3363', text: 'Option 3'},
{id: '4344', text: 'Option 4'},
{id: '2222', text: 'Option 2'},
{id: '5575', text: 'Option 5'},
{id: '9999', text: '4344'},
{id: '1111', text: 'Option 1'},
]
const select = $('.selectMe');
select
.select2({
width: '100%',
data: items,
placeholder: 'Select target code or enter new code',
allowClear: true,
tags: true,
createTag: function (params) {
if (params.term.trim() === '') { return null; }
return {
id: params.term,
text: params.term + ' 🆕'
}
},
sorter: data => data.sort((a, b) => a.text.localeCompare(b.text, 'en', { sensitivity: 'base' }))
})
.on('select2:open', function () {
const $t = $(this);
// This is undocumented and may change in the future
const $search = $t.data('select2').dropdown.$search || $t.data('select2').selection.$search
const $sel = $t.find(':selected');
$search.val($sel.is('[data-select2-tag]') ? $sel.val() : $sel.text()).trigger('keyup');
});
// Set initial values, including tags not present in items
select.each(function() {
const selectElement = $(this);
let initialValue = (selectElement.data('init') || '');
const initValLC = initialValue.toLowerCase();
if (initialValue) {
const thisItem = items.find(item => item.text.toLowerCase() === initValLC);
if (thisItem) {
initialValue = thisItem.id;
} else {
//Les paramètres du Option devraient correspondent à ce qui est fait dans createTag
const newOption = new Option(initialValue + ' 🆕', initialValue, true, true);
$(newOption).attr('data-select2-tag', true);
selectElement.prepend(newOption);
}
selectElement.val(initialValue).trigger('change');
}
});