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?
var data = []; // Programatically-generated options array with > 5 options var placeholder = "select"; $(". mySelect"). select2({ data: data, placeholder: placeholder, allowClear: false, minimumResultsForSearch: 5});
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
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
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With