Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change font to bold for some words in Select2

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?

like image 767
AlexC Avatar asked Feb 08 '16 21:02

AlexC


1 Answers

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/

like image 178
Victor Levin Avatar answered Oct 10 '22 04:10

Victor Levin