How to change font to bold for some words in Select2
Asked Answered
B

1

6

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?

Bankroll answered 8/2, 2016 at 21:0 Comment(4)
Try: $('.select2-results__option').css('font-weight', 'bold');Nyctalopia
@Nyctalopia : Wouldn't that make the entire option text bold instead of just the AK and HI codes ?Zworykin
@Nyctalopia this does not work for me. Thank you!Bankroll
@Alex if you can provide a jsfiddle for me, then i can have the feature working in no time...Nyctalopia
M
10

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/

Meatman answered 8/2, 2016 at 21:39 Comment(1)
Thanks a lot! Works like a charm.Bankroll

© 2022 - 2024 — McMap. All rights reserved.