I'm using select2 4.0.1, and I need to change the font for some words. More specifically, I need to show codes AK and HI in bolder/different font, something like this:
<select id="select2" style="width:300px">
<optgroup label="Alaskan/Hawaiian Time Zone">
<option value="AK"><strong>AK</strong> Alaska</option>
<option value="HI"><strong>HI</strong> Hawaii</option>
</optgroup>
Is it possible? How can I accomplish that?
You can accomplish it this way. Use templateResult
to modify option text as select2 gets created:
HTML:
<select id="select2" style="width:300px">
<optgroup label="Alaskan/Hawaiian Time Zone">
<option value="AK">Alaska</option>
<option value="HI">Hawaii</option>
</optgroup>
</select>
JS:
$('#select2').select2({
templateResult: formatOutput
});
function formatOutput (optionElement) {
if (!optionElement.id) { return optionElement.text; }
var $state = $('<span><strong>' + optionElement.element.value + '</strong> ' + optionElement.text + '</span>');
return $state;
};
Working fiddle: https://jsfiddle.net/18dzrhgx/1/
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