That feature isn’t built in, but you can hack it. The search field is an input
element of type search
with a class of select-search__field
. You can use the HTML5 placeholder
attribute to set placeholder text in an <input>
that accepts text entry, including the one in the Select2 widget.
However, this input
element is dynamically inserted into the DOM each time the Select2 widget is opened (i.e., the dropdown becomes visible); when the widget is closed that input
element does not exist. So you need to dynamically set the placeholder
value once the input
element becomes available. Fortunately, there’s a select2:open
event you can listen for, and in your event handler you can find the input
element and set its placeholder
attribute (or property); e.g.:
$('#your-select-id').one('select2:open', function(e) {
$('input.select2-search__field').prop('placeholder', 'enter username or city');
});
Note: in my testing, once the placeholder value is set, it is maintained even if the widget is closed and reopened. This means you only have to set the placeholder
value once. That’s why I used jQuery’s $.one()
function, which creates an event handler that runs only once (i.e., the first time the event occurs).
Also note: if you have more than one Select2 widget on your page, especially if one of them is a multi-select, you’ll have the potential that more than one input.select2-search__field
element is on your page when your event handler runs. In that case you will need to be more sophisticated about locating the correct <input>
. In that case I would recommend creating separate container elements for each Select2, and using the dropdownParent
configuration option to place each Select2 widget in its own container. Then you can use that container as the context
parameter in the jQuery selector that finds the <input>
, e.g.:
$('input.select2-search__field', $('#your-select2-container-id')).prop(...);
Good luck!