Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 363
John Brink Avatar asked Mar 23 '16 20:03

John Brink


People also ask

How do I enable select2 search?

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


3 Answers

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

like image 85
Jay Rizzi Avatar answered Oct 12 '22 15:10

Jay Rizzi


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

like image 23
Sadee Avatar answered Oct 12 '22 15:10

Sadee


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);
});
like image 6
HolaJan Avatar answered Oct 12 '22 15:10

HolaJan