Home  >  Q&A  >  body text

How to add placeholder for select2 to search input

How to make placeholders for select2 jQuery plug-in. There are a lot of answers on StackOverflow how to make placeholders there, but they are about placeholders for elements. I need to specify a placeholder for the search box, see image.

P粉521697419P粉521697419362 days ago630

reply all(2)I'll reply

  • P粉939473759

    P粉9394737592023-10-23 16:21:00

    You can use this event:

    It is enough to add the placeholder attribute to this event:

    $(this).data('select2').$dropdown.find(':input.select2-search__field').attr('placeholder', 'My Placeholder')

    $('select').select2({
        placeholder: 'Select an option'
    }).on('select2:opening', function(e) {
        $(this).data('select2').$dropdown.find(':input.select2-search__field').attr('placeholder', 'My Placeholder')
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
    
    
    <select style="width: 100%;">
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
        <option value="mercedes">Mercedes</option>
        <option value="audi">Audi</option>
    </select>

    reply
    0
  • P粉311089279

    P粉3110892792023-10-23 00:06:55

    I had the same need and ended up writing a small extension for the Select2 plugin.

    The plugin has a new option searchInputPlaceholder for setting a placeholder for the Search input field.

    Add the following code 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 using the searchInputPlaceholder option:

    $("select").select2({
        // options 
        searchInputPlaceholder: 'My custom placeholder...'
    });

    Demo:

    Demo can be found at JsFiddle.


    Updated May 9, 2020

    Tested with the latest Select2 version (v4.0.13) - JsFiddle.


    Github Repository:

    https://github.com/andreivictor/select2-searchInputPlaceholder

    reply
    0
  • Cancelreply