Select2 Dynamically Add Options
This will be helpful - but requires two functions to keep track of which select is active and to modify.
HTML
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<select id="fname" style="width: 100%">
<option value="ted">ted</option>
<option value="bill">bill</option>
<option value="sandy">sandy</option>
</select>
<hr>
<select id="lname" style="width: 100%">
<option value="smith">smith</option>
<option value="gray">gray</option>
<option value="lowe">lowe</option>
</select>
JavaScript
$('#fname').select2();
$('#lname').select2();
$('select').select2().on('select2:open', function() {
// set a global reference for the current selected Select
console.log('found this ---> ' + $(this).attr('id'));
if (typeof tempSelectedObj === 'undefined') {
tempSelectedObj = null;
}
tempSelectedObj = this;
});
$(document).on('keyup', 'input.select2-search__field', function(e) {
// capture the return event
if (e.keyCode === 13) {
var newValue = $(this).val();
console.log('processing this: ' + newValue);
// create new option element
var newOpt = $('<option>')
.val(newValue)
.text(newValue);
// append to the current Select
$(tempSelectedObj)
.append(newOpt);
// apply the change and set it
$(tempSelectedObj)
.select2()
.trigger('select2:close')
.val(newValue)
.trigger('change.select2');
}
})