Javier Rey
Javier Rey

Reputation: 35

Always display placeholder select2

I would like to build a selector that displays a "Check one or more or options" placeholder and, after selecting 1-N options, the placeholder is still displayed instead of the checked results.

In short, the component should always display the placeholder, regardless of having 0, 1 or N options checked.

I have been searching but I can't find any way to do it:

Html:

<select multiple id="e1" style="width:300px">
        <option value="AL">Alabama</option>
        <option value="Am">Amalapuram</option>
        <option value="An">Anakapalli</option>
        <option value="Ak">Akkayapalem</option>
        <option value="WY">Wyoming</option>
    </select>

Js

$('select').select2({
  placeholder: "Select a state",
  templateSelection: function (data) {
      return 'Select a state';
  }
});

http://jsfiddle.net/91nqgkuy/2/

Upvotes: 0

Views: 296

Answers (1)

Javier Rey
Javier Rey

Reputation: 35

Finally, I have chosen to overwrite the results template and insert the desired text.

  // Set the default option.
  $(select, context).each(function (e) {
    setTemplateResults($(this));
  });
  // Override select2 default work flow.
  $(select, context).on('select2:select select2:unselect', function (evt) {
    setTemplateResults($(this));
  });
  // Method.
  function setTemplateResults(selector) {
    let container = selector.siblings('span.select2').find('ul')
    container.html('<li>' + Drupal.t('Select category(ies)') + '</li>');
  }

Upvotes: 1

Related Questions