Start search after 2 character typed in Chosen drop down

烂漫一生 提交于 2021-02-07 20:02:40

问题


In Chosen drop down plugin, a search is started after 2 characters are typed in chosen drop down.

I need the search to not start until after inputing at least two characters in the search box.

Can any one suggest how to do this?


回答1:


I did a small change to start to search after the third character, is not the best option but works, in the chosen JS in the AbstractChosen.prototype.winnow_results function after the line searchText = this.get_search_text(); add the following code: if (searchText != "" && searchText.length < 3) return;. Remember to change the < 3 by your own size.

Hope this help you

See part of the code below:

AbstractChosen.prototype.winnow_results = function() {
  var escapedSearchText, option, regex, regexAnchor, results, results_group, searchText, startpos, text, zregex, _i, _len, _ref;
  this.no_results_clear();
  results = 0;
  searchText = this.get_search_text();
  if (searchText != "" && searchText.length < 3) return;
  escapedSearchText = searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");



回答2:


I know this post it's old but i had to face this problem just now and wanted to share my result. I wrapped everything in a function extendedSearch and set it as a callback while chosen is emitting the chosen:showing_dropdown event.

My problem was that i need the search to show the results after the 2nd character typed in search and must filter out certain strings from the results.

Bellow you'll find a demo which shows results on the 3rd character typed in, and will keep visible only those results that end with letter "E".

$(function() {
  /**
   * By default the results are hidden when clicking a dropdown.
   * {
   *      toggleResults: false, // a function(searchValue) that returns a boolean
   *      filterResults: false, // a function(dropDownValue, selectValue) that returns a boolean
   *  }
   * @param options
   */
  const extendedSearch = (options = {}) => {

    const defaultOptions = {
      toggleResults: false,
      filterResults: false,
    };

    options = { ...{},
      ...defaultOptions,
      ...options
    };

    /**
     * Main element
     */
    return (evt, params) => {

      let originalElement = $(evt.currentTarget);
      let searchInput = params.chosen.search_field;

      const customSearch = (options = {}) => {

        let defaultOptions = {
          originalElement: null,
          searchInput: null
        };

        options = { ...{},
          ...defaultOptions,
          ...options
        };

        if (!(options.originalElement instanceof jQuery) || !options.originalElement) {
          throw new Error('Custom Search: originalElement is invalid.');
        }
        if (!(options.searchInput instanceof jQuery) || !options.searchInput) {
          throw new Error('Custom Search: searchInput is invalid.');
        }

        let res = options.searchInput
          .parent()
          .next('.chosen-results');

        res.hide();

        if (typeof options.toggleResults !== 'function') {
          options.toggleResults = (value) => true;
        }
        if (options.filterResults && typeof options.filterResults !== 'function') {
          options.filterResults = (shownText = '', selectValue = '') => true;
        }

        /**
         * Search Input Element
         */
        return (e) => {

          let elem = $(e.currentTarget);
          let value = elem.val() || '';

          if (value.length && options.toggleResults(value) === true) {

            res.show();

            if (options.filterResults) {

              let children = res.children();
              let active = 0;

              $.each(children, (idx, item) => {

                let elItem = $(item);
                let elemIdx = elItem.attr('data-option-array-index');
                let shownText = elItem.text();
                let selectValue = options.originalElement.find('option:eq(' + elemIdx + ')').attr('value') || '';

                if (options.filterResults(shownText, selectValue) === true) {
                  active++;
                  elItem.show();
                } else {
                  active--;
                  elItem.hide();
                }

              });

              if (active >= 0) {
                res.show();
              } else {
                res.hide();
              }

            }

          } else {
            res.hide();
          }


        };

      };

      options = {
        ...{},
        ...options,
        ...{
          originalElement,
          searchInput
        }
      };

      let searchInstance = customSearch(options);

      searchInput
        .off('keyup', searchInstance)
        .on('keyup', searchInstance)

    }

  };

  /** This is the final code */
  const inputValidator = (value) => {
    console.log('input', value);
    return $.trim(value).length > 2;
  };
  const textResultsValidator = (dropDownValue, selectValue) => {
    if ($.trim(dropDownValue).substr(-1, 1) === 'E') {
      console.log('results shown', dropDownValue, '|', selectValue);
      return true;
    }
    return false;
  };

  $(".chosen-select")
    .chosen()
    .on('chosen:showing_dropdown', extendedSearch({
      toggleResults: inputValidator,
      filterResults: textResultsValidator
    }));

});
@import url("https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.min.css")
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js"></script>


<select class="chosen-select">
  <option value="">Pick something</option>
  <option value="APPLE">APPLE</option>
  <option value="APPLE JUICE">APPLE JUICE</option>
  <option value="BANANA">BANANA</option>
  <option value="ANANAS">ANANAS</option>
  <option value="ORANGE">ORANGE</option>
  <option value="ORANGES">ORANGES</option>
  <option value="STRAWBERRY">STRAYBERRY</option>
</select>


来源:https://stackoverflow.com/questions/25870655/start-search-after-2-character-typed-in-chosen-drop-down

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!