select2 ajax processResults
https://stackoverflow.com/q/70784804/863110
by moshfeu
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<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>
<script src="https://code.jquery.com/ui/1.13.0/jquery-ui.js"></script>
<select class="js-data-example-ajax" id="mySelect2">
</select>
CSS
.js-data-example-ajax {
width: 100%;
}
JavaScript
var data = [
["text1", "extra text1"] ,
["text2", "extra text2"] ,
["text3", "extra text3"] ,
];
$(document).ready(function() {
$('.js-data-example-ajax').select2({
placeholder: "select...",
templateSelection: function (state) {
if (!state.id) {
return state.text;
}
return $(`<span title="${state.title}">${state.text} & ${state.text2}</span>`);
},
ajax: {
type: "POST",
dataType: 'json',
url: '/echo/json/', // jsfiddle simulate ajax
//url: 'ajaxhandler.php',
processResults: function (data) {
var options = [];
if (data) {
$.each(data.items, function (index, text) {
options.push({ id: index, text: text[0], text2: text[1], title:'hello'});
});
}
return {
results: options,
more: false
};
},
data: function (params) {
var query = {
search: params.term,
items: data // only for jsfiddle to simulate ajax
};
if (params.term == "*") query.items = [];
return { json: JSON.stringify( query ) }
}
}
});
$('.js-data-example-ajax').on("select2:opening", function (e) {
$(document).on('mouseenter', '.select2-results__option', function () {
//Tooltip is not working here.
$(this).tooltip({
position: {
my: "center bottom-20",
at: "center top",
using: function( position, feedback ) {
$(this).css(position);
var txt = $(this).text();
$(this).html(txt);
$( "<div>" )
.addClass( "arrow" )
.addClass( feedback.vertical )
.addClass( feedback.horizontal )
.appendTo( this );
}
}
});
});
});
...