Использование стандартных select-боксов скучно и уныло. А в 2017 так и вовсе неуважительно в отношении к пользователю. Предлагаем использовать плагин JS для кастомизации HTML Select.
В данном посте речь пойдет не о jQuery плагине, как Вы могли подумать. Всем известно, что лучше использовать инструмент без каких-либо зависимостей. Как раз им и является Choices.js. Это миниатюрная библиотека, которая с легкостью поможет Вам создать custom select и управлять выпадающими списками и элементами option в нем.
Автор плагина выделяет следующие преимущества своей работы:
- Легкий вес = высокая производительность;
- Нет зависимости от jQuery;
- Настраиваемая сортировка;
- Использование Flexible;
- Быстрый поиск\фильтрация;
- Доступный API;
- Возможность создавать свое оформление.

Инсталляция и использование плагина:
Подключаем файлы
<!-- Include base CSS (optional) --> <link rel="stylesheet" href="assets/styles/css/base.min.css"> <!-- Include Choices CSS --> <link rel="stylesheet" href="assets/styles/css/choices.min.css"> <!-- Include Choices JavaScript --> <script src="/assets/scripts/dist/choices.min.js"></script>
Установки параметров в скрипте
// Pass multiple elements:
const choices = new Choices(elements);
// Pass single element:
const choices = new Choices(element);
// Pass reference
const choices = new Choices('[data-trigger']);
const choices = new Choices('.js-choice');
// Pass jQuery element
const choices = new Choices($('.js-choice')[0]);
// Passing options (with default options)
const choices = new Choices(elements, {
items: [],
choices: [],
maxItemCount: -1,
addItems: true,
removeItems: true,
removeItemButton: false,
editItems: false,
duplicateItems: true,
delimiter: ',',
paste: true,
search: true,
searchFloor: 1,
position: 'auto',
resetScrollPosition: true,
regexFilter: null,
shouldSort: true,
sortFilter: () => {...},
sortFields: ['label', 'value'],
placeholder: true,
placeholderValue: null,
prependValue: null,
appendValue: null,
loadingText: 'Loading...',
noResultsText: 'No results found',
noChoicesText: 'No choices to choose from',
itemSelectText: 'Press to select',
addItemText: (value) => {
return `Press Enter to add <b>"${value}"</b>`;
},
maxItemText: (maxItemCount) => {
return `Only ${maxItemCount} values can be added.`;
},
classNames: {
containerOuter: 'choices',
containerInner: 'choices__inner',
input: 'choices__input',
inputCloned: 'choices__input--cloned',
list: 'choices__list',
listItems: 'choices__list--multiple',
listSingle: 'choices__list--single',
listDropdown: 'choices__list--dropdown',
item: 'choices__item',
itemSelectable: 'choices__item--selectable',
itemDisabled: 'choices__item--disabled',
itemChoice: 'choices__item--choice',
group: 'choices__group',
groupHeading : 'choices__heading',
button: 'choices__button',
activeState: 'is-active',
focusState: 'is-focused',
openState: 'is-open',
disabledState: 'is-disabled',
highlightedState: 'is-highlighted',
hiddenState: 'is-hidden',
flippedState: 'is-flipped',
loadingState: 'is-loading',
},
// Choices uses the great Fuse library for searching. You
// can find more options here: https://github.com/krisk/Fuse#options
fuseOptions: {
include: 'score',
},
callbackOnInit: null,
callbackOnCreateTemplates: null,
});
Как видно из кода выше, плагин очень гибкий и без труда может быть оформлен под Ваши личные потребности. Рекомендуем также ознакомиться со всеми опциями и методами csutom select. Всю информацию можно найти на страничке автора Github (ссылка выше).
