Seems like a pretty simple idea, but I can't figure out how to filter out option tags of the original select from the select2 dropdown.
Basically, this:
<select id="select">
<option class="car">Car 1</option>
<option class="plane">Plane 1</option>
</select>
$("#select").select2();
... should create a fake select with only the option tags with the class car
.
Select a cell in the header row. The cell must contain the filter drop down icon. Press and hold the Alt key, then press the Down Arrow key on the keyboard to open the filter menu.
In order to clear the selection of those values which are selected using a Select2 drop down,we can use the empty() function. The dropdown can be reset using Jquery. $("#select2_example"). empty();
In order to hide the search box in select2, you can hide the search box by setting "minimumResultsForSearch" to a negative value. $('select'). select2({ minimumResultsForSearch: -1 });
New options can be added to a Select2 control programmatically by creating a new Javascript Option object and appending it to the control: var data = { id: 1, text: 'Barn owl' }; var newOption = new Option(data. text, data.id, false, false); $('#mySelect2'). append(newOption).
It appears the OP found the answer at https://github.com/select2/select2/issues/1048.
The answer is to supply a matcher
function.
$("#select").select2({
matcher: function(term, text, option) {
return option.hasClass('car');
}
});
jsfiddle
Just to keep this question up-to-date.. The proposed answer with the use of supplying the matcher
function is outdated. Since Select2 4.0.0 you need to use a wrapper with the matcher
:
function matchStart (term, text) {
if (text.toUpperCase().indexOf(term.toUpperCase()) == 0) {
return true;
}
return false;
}
$.fn.select2.amd.require(['select2/compat/matcher'], function (oldMatcher) {
$(".js-example-matcher-start").select2({
matcher: oldMatcher(matchStart)
})
});
For ME, this didn't work. I don't know why. But I've found a work-around for this. Apparently, with Select2 you can also supply a format function to the .select2()
method for each option
or element in the select. For example, when you want to prepend each element with an icon or something like this. Turns out that the element won't be shown in the dropdown if you return null
in the format function, like this:
function formatState(state) {
if (!state.id) { return state.text; }
if (state.disabled) { return null; }
var $state = $('<span>'.concat(state.text).concat("</span>"));
return $state;
}
$('#myDropdown').select2({
templateResult: formatState
});
This worked for me immediately. Perhaps it could help any of you with current implementations.
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