How to make placeholder for select2 jQuery plugin. On StackOverflow many answers how to make placeholder there, but they about element\'s placeholder. I need to specify a pl
I had the same need and I had ended up writing a small extension for the Select2
plugin.
There is a new option for the plugin, searchInputPlaceholder
, in order to set a placeholder for the 'search' input field.
Add the following code right after the plugin's js file:
(function($) {
var Defaults = $.fn.select2.amd.require('select2/defaults');
$.extend(Defaults.defaults, {
searchInputPlaceholder: ''
});
var SearchDropdown = $.fn.select2.amd.require('select2/dropdown/search');
var _renderSearchDropdown = SearchDropdown.prototype.render;
SearchDropdown.prototype.render = function(decorated) {
// invoke parent method
var $rendered = _renderSearchDropdown.apply(this, Array.prototype.slice.apply(arguments));
this.$search.attr('placeholder', this.options.get('searchInputPlaceholder'));
return $rendered;
};
})(window.jQuery);
Usage:
Initialize the select2 plugin with the searchInputPlaceholder
option:
$("select").select2({
// options
searchInputPlaceholder: 'My custom placeholder...'
});
Demo:
Demo available on JsFiddle.
UPDATE May 9, 2020
Tested with the latest Select2 Version (v4.0.13) - JsFiddle.
Github repo:
https://github.com/andreivictor/select2-searchInputPlaceholder