select 2 dropdown add item code example
Example 1: select2 add option
if ($('#mySelect2').find("option[value='" + data.id + "']").length) {
$('#mySelect2').val(data.id).trigger('change');
} else {
var newOption = new Option(data.text, data.id, true, true);
$('#mySelect2').append(newOption).trigger('change');
}
Example 2: select2 dropdown with option to add new item
$('#select2')
.select2()
.on('select2:open', () => {
$(".select2-results:not(:has(a))").append('<a href="#" style="padding: 6px;height: 20px;display: inline-table;">Create new item</a>');
})