Select2- Ajax - Single Selection
This is a example where select2 is configured for single selection of Ajax. Also included in this example is a simple and a complex data implementation.
by Faisal Pathan
September 16, 2020
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.1/css/bootstrap.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.css">
<input type="text" id="select2_ajax_complex_id" />
JavaScript
$(document).ready(function () {
var complex_employee_response = '[{"id":"1", "name": "Srinivas Chekuri", "role":"Architect"}, {"id":"2", "name": "Robert Hollinger", "role":"Manager"}, {"id":"3", "name": "Mike Sapp", "role":"Developer"}, {"id":"4", "name": "Nina Switz", "role":"Business"}]';
$('#select2_ajax_complex_id').select2({ minimumInputLength: 1,
placeholder: "Search Employees",
//data:o,
id: function(i){
return i;
},
initSelection: function(element, callback) {
},
ajax: {
type: 'post',
url: "/echo/json/",
allowClear: true,
dataType: 'json',
delay: 250,
params: {contentType: "application/json"},
data: function(term, page){
//Code for dummy ajax response
return {
json: complex_employee_response,
delay: 0
};
},
results: function (data, page) {
return { results: data};
},
cache: false
},
formatResult: function (i) {return '<div><b>'+i.name+'</b>('+i.role+')'+'</div>'; }, // Formats results in drop down
formatSelection: function (i) {return '<div>'+i.name+'('+i.role+')'+'</div>'; }, //Formats result that is selected
dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results
})
});