Home Ask Login Register

Developers Planet

Your answer is one click away!

AlexC February 2016

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?

Answers


Victor Levin February 2016

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/

Post Status

Asked in February 2016
Viewed 1,399 times
Voted 6
Answered 1 times

Search




Leave an answer


Quote of the day: live life