Additional placeholder in search input


#1

First, sorry if its an allready answered topic (searched before of course, but nothing found and stressy client behind…)

Question: Is it possible to set a placeholder in the dropdowns search field?

Example:
placeholder main: “Select user”
Placeholder in seatch field: “enter username or city”

Reason: input might easily be overlooked, especially on mob devices (independet from styling)

Thanks in advance and cheers,
Phil


#2

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!


#3

Yeah, great tip like this, and remains on top valid and logical markup. Will implement it later. Lots of thanks & cheers


#4

Hi John, works like a charm. Lots of thanks. BTW, how can I mark the question as answered her? don’t see any option in this forum…


#5

Hi, Phil. I’m glad my suggestion worked for you!

I don’t think you can mark a question as “answered”, but you can “like” my answer, which should signal the same thing. That will also improve my reputation on the site and let other posters know they can trust my answers.