I am using select2.js V4.0 (not 3.6!!!) and I want to display and format a javascript local source :
var data_names = [{
id: 0,
text: "Henri",
last_name: 'Barbusse'
}, {
id: 1,
text: "John",
last_name: 'Lenon'
}, {
id: 2,
text: "Victor",
last_name: 'Hugo'
}, {
id: 3,
text: "Marie",
last_name: 'Stuart'
}, {
id: 4,
text: "Boriss",
last_name: 'Vian'
}];
My format methode could be for example:
function name_format(item) {
if (!item.last_name) {
return item.text;
}
var full_name = '<span class="my_class">' + item.text + ' ' + item.last_name + '</span>';
return full_name;
}
Do you know how do this in v4.0?
According to the docs you have to use the option templateResult
The templateResult function should return a string containing the text to be displayed, or an object (such as a jQuery object) that contains the data that should be displayed. It can also return null, which will prevent the option from being displayed in the results list.
Something like this should do it
$('select').select2({
multiple: true,
data: data_names,
templateResult: name_format
});
function name_format(item) {
if (!item.last_name) {
return item.text;
}
var full_name = $('<span class="my_class">' + item.text + ' ' + item.last_name + '</span>');
return full_name;
}
$(function() {
var data_names = [{
id: 0,
text: "Henri",
last_name: 'Barbusse'
}, {
id: 1,
text: "John",
last_name: 'Lenon'
}, {
id: 2,
text: "Victor",
last_name: 'Hugo'
}, {
id: 3,
text: "Marie",
last_name: 'Stuart'
}, {
id: 4,
text: "Boriss",
last_name: 'Vian'
}];
$('select').select2({
multiple: true,
data: data_names,
templateResult: name_format
})
});
select {
width: 250px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://select2.github.io/dist/js/select2.full.js"></script>
<link href="https://select2.github.io/dist/css/select2.min.css" rel="stylesheet" />
<select></select>
Also, the name_format method should return a DOM/jQuery object and not string.
function name_format(item) {
if (!item.last_name) {
return item.text;
}
var full_name = $('<span class="my_class">' + item.text+ ' ' + item.last_name+'</span>');
return full_name;
}