Select с поиском jquery

Как реализовать поиск в select по option без bootstrap select ?

2 ответа 2

ни фига не понятно, но если вы хотите в элементе select узнать выбранную опцию, то:

Включите следующие строки кода в разделе вашего HTML.

Инициализируйте Select2 для элемента , который вы хотите сделать удивительным.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками html или задайте свой вопрос.

Похожие

Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.

дизайн сайта / логотип © 2020 Stack Exchange Inc; пользовательское содержимое попадает под действие лицензии cc by-sa 4.0 с указанием ссылки на источник. rev 2020.1.17.35809

A search box is added to the top of the dropdown automatically for select boxes where only a single option can be selected. The behavior and appearance of the search box can be easily customized with Select2.

Customizing how results are matched

When users filter down the results by entering search terms into the search box, Select2 uses an internal "matcher" to match search terms to results. You may customize the way that Select2 matches search terms by specifying a callback for the matcher configuration option.

Select2 will pass each option as represented by its internal representation into this callback to determine if it should be displayed:

matcher only works with locally supplied data (e.g., via an array! When a remote data set is used, Select2 expects that the returned results have already been filtered on the server side.

Matching grouped options

Only first-level objects will be passed in to the matcher callback. If you are working with nested data, you must iterate through the children array and match them individually. This allows for more advanced matching when working with nested objects, allowing you to handle them however you want.

Читайте также:  Excel соответствие русских и английских функций

This example matches results only if the term appears in the beginning of the string:

Minimum search term length

Sometimes when working with large data sets, it is more efficient to start filtering the results only when the search term is a certain length. This is very common when working with remote data sets, as it allows for only significant search terms to be used.

You may set a minimum search term length by using the minimumInputLength option:

Maximum search term length

In some cases, search terms need to be limited to a certain range. Select2 allows you to limit the length of the search term such that it does not exceed a certain length.

You may limit the maximum length of search terms by using the maximumInputLength option:

Limiting display of the search box to large result sets

The minimumResultsForSearch option determines the minimum number of results required in the initial population of the dropdown to display the search box.

This option is useful for cases where local data is used with a small result set, and the search box would simply be a waste of screen real estate. Set this value to -1 to permanently hide the search box.

Hiding the search box

Single select

For single selects, Select2 allows you to hide the search box using the minimumResultsForSearch configuration option. In this example, we use the value Infinity to tell Select2 to never display the search box.

Multi-select

For multi-select boxes, there is no distinct search control. So, to disable search for multi-select boxes, you will need to set the disabled property to true whenever the dropdown is opened or closed:

Читайте также:  Uncaught error call to undefined method

See this issue for the source of this solution.

На одном из сайтов, с которыми мне довелось поработать, был select, в котором хранились названия всех городов России. Ну, может и не всех, но в районе 2000 городов точно было. Представьте себе, что вы открываете такой список и пытаетесь найти нужный вам город. Зрелище так себе, согласитесь.

В таком случае на ум мне пришло следующее: а что если скрыть весь этот список и осуществить по нему поиск через тот же input, и выбрать нужный нам пункт при успешном совпадении введенного города с имеющимися.

Поискав информацию по этому поводу, я узнал, что в jQuery есть очень интересная штука под названием «autocomplete» – плагин, который помогает пользователю заполнять текстовое поле на основе сравнения введенной информации с существующей. Именно это и легло в основу моего скрипта.

Итак, приступим к реализации. Для начала нам нужно составить какой-нибудь select и input:

При этом, как вы заметили, мы сразу скрываем select.

Далее в секции HEAD подключаем необходимые библиотеки:

И завершающим этапом будет вставка скрипта перед закрывающим тегом

Rate this post

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *