Reputation: 65
I am trying to find an updated answer to this question here as it seems that the formatSelection option for Select2 does no longer work, or is simply not working for me.
Basically, I have a multi-select Select2 menu and would like to have the option's value displayed after being selected rather than it being the text description. For instance, I have a list of provinces where each one has a shorthand as a value on the option (AB for Alberta, BC for British Columbia, etc.) Those are the ones I would like to have displayed after being selected. Is there a simple way of doing this in Select2 4.0.0?
Markup:
<select id="provSelect" multiple data-role="none" >
</select>
for the JS:
$("#provSelect").select2({
width:"100%",
formatSelection: formatSelection});
With the appropriate function:
function formatSelection(item){
return item.id;
}
Upvotes: 3
Views: 3440
Reputation: 11
Template Selections can be found here -> https://select2.org/selections or review the sample below:
function formatState (state) {
if (!state.id) {
return state.text;
}
var baseUrl = "/user/pages/images/flags";
var $state = $(
'<span><img class="img-flag" /> <span></span></span>'
);
// Use .text() instead of HTML string concatenation to avoid script injection issues
$state.find("span").text(state.text);
$state.find("img").attr("src", baseUrl + "/" + state.element.value.toLowerCase() + ".png");
return $state;
};
$(".js-example-templating").select2({
templateSelection: formatState
});
Upvotes: 0
Reputation: 1365
Select2 still has a formatting API, it's called templating now. Example:
function formatState (state) {
if (!state.id) { return state.text; }
var $state = $(
'<span><img src="vendor/images/flags/' + state.element.value.toLowerCase() + '.png" class="img-flag" /> ' + state.text + '</span>'
);
return $state;
};
$(".js-example-templating").select2({
templateSelection: formatState
});
You can template the result and selection differently; docs here.
Upvotes: 5