$('#select2').select2({
minimumResultsForSearch: 20,
});
$('#select2search').select2();
// https://stackoverflow.com/a/1909508/1366033
var delay = (function () {
var timer = 0;
return function (callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
// if we have focus and the container is open, it means we're not in the search field
$("body").on('keydown', '.select2-container--focus.select2-container--open',
function(e) {
// get char https://stackoverflow.com/a/34711175/1366033
var char = e.key
// only accept a range of characters
if (/^[a-z]{1}$/i.test(char)) {
// select2 handles others https://github.com/select2/select2/blob/4.0.5/dist/js/select2.js#L5368
var $this = $(this); // need inside delay
// act immediately but temporarily store a run of characters
delay(function () {
// clear search text on delay
$this.data("searchText", "");
}, 750);
// build search string with any previous characters and store new value
var previous = $this.data("searchText");
var searchText = (previous === undefined ? "" : previous) + char;
$this.data("searchText", searchText);
console.log(searchText);
// find available options
var $sel2 = $this.data("element");
var $select2 = $sel2.data("select2");
var $results = $select2.results.$results;
var $opts = $results.find(".select2-results__option");
// find first option with matching start and select it
$opts.each(function(i,el) {
var $opt = $(el)
var optText = $opt.text()
var startsWithRegex = new RegExp('^' + searchText, 'i');
var match = startsWithRegex.test(optText)
// if we got one - fire event and we can leave
if (match) {
// mouseenter is a reliable way to highlight item in results list
// https://github.com/select2/select2/blob/4.0.5/dist/js/select2.js#L1234
$opt.trigger('mouseenter');
return;
}
...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.