Select2 Templating text In Selection Render

- 1 answer

I've got stacked on select stylization. I'm not so pro, im just learning and I cant solve this problem alone yet. I use select2 and found the most acceptable type for select form. I tried to understand what is going wrong but I couldn't. I want such select which show span with text, not just a text. Like its on pic#1. But i all the time get only text without color mark - pic#2.

enter image description here

My code is:

<div class="fieldset fieldset-1">
   <label for="color">Choose color</label>
   <select name="color" class="color-choose">                             
      <option value="grn">Green</option>
      <option value="blu">Blue</option>
      <option value="brn">Brown</option>
      <option value="blk">Black</option>
      <option value="red">Red</option>
      <option value="yel">Yellow</option>
      <option value="wht">White</option>                                  

and JS code:

function formatState (state) {
  if (! { return state.text; }
  var $state = $(
    '<span class="color-element color-' + state.element.value + '">' + state.text + '</span>'
  return $state;

  templateResult: formatState

so i got such result: enter image description here

Please, help me to solve it! Will be very appreciated!



You are only setting the template for the results (using templateResult), but you are not setting the template for the selection. Select2 allows you to use different templates for selections and results (see the AJAX example), so you must set the renderer for selections using the templateSelection option.

  templateResult: formatState,
  templateSelection: formatState