select2 with ability to write unisted value 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: select 2 dropdown
$('#element').select2({
placeholder: 'Select a option',
minimumInputLength: 3,
ajax: {
url: route('api.fetch-options'),
dataType: 'json',
type: 'GET',
quietMillis: 50,
data: function (params) {
return {
visitor_name: params.term
}
},
processResults({ data }) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
id: item.id,
}
})
}
}
}
}).change(() => {
});