jqueryui autocomplete:列出中间带搜索词的条目

Aks*_*hey 5 jquery-ui autocomplete prefix

我正在使用jqueryui自动完成小部件来自动填充"国家/地区"字段,但我遇到了一个问题.假设用户输入"in",我希望jqueryui列出像'india'这样的国家,'indonesia'以'in'开头,但它也列出了名称中某处有'in'的国家(如:argentina) .我该如何解决这个问题?

jQuery(".autocomplete").autocomplete({
    source: CountrySuggestions, //CountrySuggestions is an array in javascript containing the list of countries
    minLength: 2
});
Run Code Online (Sandbox Code Playgroud)

Akshey

Lan*_*nce 4

不幸的是,似乎 jQueryUI Autocomplete 不允许在数组源上执行此操作。但是,您可以挂钩插件的_initSource函数,以在搜索中强制使用“开头为”正则表达式标记 ( ^ ),如下所示。

我认为这可能被忽视了,因为它的大部分用途被认为是在远程检索中。无论哪种方式,都不是一个很好的解决方案,但由于正则表达式剥离功能,这是想到的唯一解决方案。

$.ui.autocomplete.prototype._initSource = function() {
  var array,
    url;
  if ( $.isArray(this.options.source) ) {
    array = this.options.source;
    this.source = function( request, response ) {
      // escape regex characters
      var matcher = new RegExp( "^"+$.ui.autocomplete.escapeRegex(request.term), "i" );
      response( $.grep( array, function(value) {
        return matcher.test( value.label || value.value || value );
      }) );
    };
  } else if ( typeof this.options.source === "string" ) {
    url = this.options.source;
    this.source = function( request, response ) {
      $.getJSON( url, request, response );
    };
  } else {
    this.source = this.options.source;
  }
};

$("#countries").autocomplete({
  source: ["India","Indonesia","Argentina"],
  minLength: 2
});
Run Code Online (Sandbox Code Playgroud)