John Brink
John Brink

Reputation: 658

Enable select2 multi-select search box

I need to be able to add a search box to my multi-select fields using select2.

For whatever reason, while search boxes appear as expected in single-select fields, the same select2() call on a multi-select field does not add a search box.

var data = []; // Programatically-generated options array with > 5 options
var placeholder = "select";
$(".mySelect").select2({
    data: data,
    placeholder: placeholder,
    allowClear: false,
    minimumResultsForSearch: 5});

Does select2 not support search boxes with multi-selects? Does anyone have a good similarly-functioning alternative?

Upvotes: 24

Views: 179607

Answers (4)

HolaJan
HolaJan

Reputation: 916

You can use dropdownAdapter options to set original Dropdown with SearchBox. This code working for me (select2 v. 4.0.13):

//Set Dropdown with SearchBox via dropdownAdapter option (https://stackoverflow.com/questions/35799854/how-to-add-selectall-using-dropdownadapter-on-select2-v4)
var Utils = $.fn.select2.amd.require('select2/utils');
var Dropdown = $.fn.select2.amd.require('select2/dropdown');
var DropdownSearch = $.fn.select2.amd.require('select2/dropdown/search');
var CloseOnSelect = $.fn.select2.amd.require('select2/dropdown/closeOnSelect');
var AttachBody = $.fn.select2.amd.require('select2/dropdown/attachBody');

var dropdownAdapter = Utils.Decorate(Utils.Decorate(Utils.Decorate(Dropdown, DropdownSearch), CloseOnSelect), AttachBody);

$('#select2').select2({
    ...
    dropdownAdapter: dropdownAdapter,
    minimumResultsForSearch: 0,
    ...
}).on('select2:opening select2:closing', function (event) {
    //Disable original search (https://select2.org/searching#multi-select)
    var searchfield = $(this).parent().find('.select2-search__field');
    searchfield.prop('disabled', true);
});

Upvotes: 12

Waiyl Karim
Waiyl Karim

Reputation: 2950

If none of the answers above work for you (new comers), consider wrapping everything between $(document).ready(function() { // your select2 declaration here... }); Sometimes it's a common issue!

Upvotes: -2

Sadee
Sadee

Reputation: 3170

select2 v4.0.3

<select class="smartsearch_keyword" name="keyword[]" id="keyword" style="width:100%;"></select>

$(".smartsearch_keyword").select2({
    multiple: true,
    ...
});

In addition: to set multiple default selections

Upvotes: 21

Jay Rizzi
Jay Rizzi

Reputation: 4304

The answer is that the select2 input element becomes the search box for multiple selects without back end data

if you start typing , your results will start filtering the options

if you have it set to load remote ajax data, it actually does retain a search box, but for multiple selects without a data source, the input is the search bar, which is fairly intuitive

https://select2.github.io/examples.html

Upvotes: 25

Related Questions