×

注意!页面内容来自https://select2.org/placeholders,本站不储存任何内容,为了更好的阅读体验进行在线解析,若有广告出现,请及时反馈。若您觉得侵犯了您的利益,请通知我们进行删除,然后访问 原网页

Placeholders

Select2 supports displaying a placeholder value using the placeholder configuration option. The placeholder value will be displayed until a selection is made.

Text placeholders

The most common situation is to use a string of text as your placeholder value.

Single select placeholders

<select class="-example-placeholder-single -states form-control">
  <option></option>
</select>


For single selects onlyin order for the placeholder value to appearyou must have a blank <option> as the first option in your <select> control. This is because the browser tries to select the first option by default. If your first option were non-emptythe browser would display this instead of the placeholder.

Multi-select placeholders

For multi-selectsyou must not have an empty <option> element:

<select class="-example-placeholder-multiple -states form-control" multiple="multiple"></select>


Select2 uses the placeholder attribute on multiple select boxeswhich requires IE 10+. You can support it in older versions with the Placeholders. polyfill.

Default selection placeholders

Alternativelythe value of the placeholder option can be a data object representing a default selection (<option>). In this case the id of the data object should match the value of the corresponding default selection.

$('select').select2({
  placeholder: {
    id: '-1'// the value of the option
    text: 'Select an option'
  }
});

This is usefulfor examplewhen you are using a framework that creates its own placeholder option.

Using placeholders with AJAX

Select2 supports placeholders for all configurationsincluding AJAX. You will still need to add in the empty <option> if you are using a single select.

Customizing placeholder appearance

When using Select2 in single-selection modethe placeholder option will be passed through the templateSelection callback if specified. You can use some additional logic in this callback to check the id property and apply an alternative transformation to your placeholder option:

$('select').select2({
  templateSelection: function (data) {
    if (data.id === '') { // adjust for custom placeholder values
      return 'Custom d placeholder text';
    }

    return data.text;
  }
});

When multiple selections are allowedthe placeholder will be displayed using the placeholder attribute on the search box. You can customize the display of this placeholder using CSSas explained in the following Stack Overflow answer: Change an input's HTML5 placeholder color with CSS.

Placeholders in legacy Internet Explorer versions

Select2 uses the native placeholder attribute on input boxes for the multiple selectand that attribute is not supported in older versions of Internet Explorer. You need to include Placeholders. on your pageor use the full buildin order to add placeholder attribute support to input boxes.