Is there a way I can set selected id/text in select2 in HTML just like is being displayed and selected?
I am using jquery select2 version 4.0.0
this is the code:
$("#users").select2({
placeholder: "select user...",
escapeMarkup: function (markup) { return markup; },
ajax: {
url: "users.json",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (response, page) {
return {
results: response.data
};
},
cache: true
},
templateResult: function(item){
if (item.loading) {
return item.text;
}
return item.username + " <small><i>(" + item.role + ")</i></small> "; // display data in html
},
templateSelection: function(item){
if (item.username){
return item.username + " <small><i>(" + item.role + ")</i></small> "; // select row in html
}
return item.text; // for placeholder
}
});
To set selected value I do:
// bring data for to set selected value, data contains fields data
var selected_user_id = data.id,
// this is the content that I need to use as it is HTML content
selected_user_text_html = data.username + " <small><i>(" + data.role + ")</i></small> ",
// this is the one that I am using and is not html because there is no way to put html inside a option select item
selected_user_text_regular = data.username + " (" + data.role + ") ";
// set selected value
$("#users").append("<option value='"+selected_user_id+"' selected='selected'>"+selected_user_text_regular+"</option>");
// trigger update
$("#users").trigger("change");
Is there a way I can set the selected text in HTML instead of plain text?