3

I am trying to get select2 to display placeholder when HTML <select> does not have an option selected.

My HTML select - no options have "selected" attribute and there's no "empty" option either:

<select id="el" style="width:300px">
    <option value="1">United States</option>
    <option value="2">Canada</option>
</select>

On page load I do this:

$('#el').val(null);

As a result, my combo looks like this - you can see that no option is selected:

enter image description here

Then, I init select2:

$('#el').select2({
    allowClear: true,
    placeholder: '(select...)'
});

and combo turns into select2 control with "United States" being selected:

enter image description here

However, I would like it to look like this:

enter image description here

I.e. when my combo's value is NULL (or selectedIndex is -1), I would like select2 to display the placeholder (select...) as opposed to the first <option>.

Nick
  • 3,231
  • 2
  • 28
  • 50
temuri
  • 2,767
  • 5
  • 41
  • 63
  • Possible duplicate of http://stackoverflow.com/questions/21413241/how-to-use-placeholder-as-default-value-in-select2-framework. See [answer](http://stackoverflow.com/a/25410119/5360631) – smcd Apr 13 '16 at 18:41
  • 1
    The "accepted" answer does not work in the suggested solution. Firstly, it does not render the placeholder, secondly it also renders empty element as first option. Not helpful. – temuri Apr 13 '16 at 20:40
  • 2
    It does work? https://jsfiddle.net/kqqeet2s/1/ from the documentation https://select2.github.io/options.html#my-first-option-is-being-displayed-instead-of-my-placeholder – smcd Apr 13 '16 at 21:25

0 Answers0