Select or add to Select2 V3
by loginet
HTML
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@3.4.3/select2.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@3.4.3/select2.css">
<input type="text" class="input_email" name="to_email" id="to_email" />
CSS
.input_email {
width: 100%;
}
JavaScript
$('#to_email').select2({
placeholder: '',
allowClear: true,
tags: true,
tokenSeparators: [",", " "],
createSearchChoice: function(term, data) {
if ($(data).filter(function() {
//change this to whatever you have to validate
//I'm returning from ajax a json well formated
//[
// {
// id: "0",
// text: "No Results Found..."
// }
//]
return this.text.localeCompare(term) !== 0;
}).length === 0) {
console.log(data);
return {
id: term,
text: term
};
}
},
ajax: {
url: "https://jsonplaceholder.typicode.com/todos/0",
dataType: "json",
data: function(term) {
return {
term: term,
};
},
results: function(data, term) {
var results = [];
$.each(data, function(index, item) {
results.push({
id: item.id,
text: item.title,
});
if (item.id == 0) { //no results
results.length = 0;
}
});
return {
results: results,
};
},
},
multiple: true,
});