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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With