3

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>                                  
    </select>
 </div>

and JS code:

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

$(".color-choose").select2({
  templateResult: formatState
});

so i got such result: enter image description here

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

4

1 回答 1

2

您只是为结果设置模板(使用templateResult),而不是为选择设置模板。Select2 允许您为选择和结果使用不同的模板(请参阅AJAX 示例),因此您必须使用该templateSelection选项为选择设置渲染器。

$(".color-choose").select2({
  templateResult: formatState,
  templateSelection: formatState
});
于 2016-01-08T21:37:11.463 回答