Jquery autocomplete not showing 2 or multiple spaces in drop down suggested

a 夏天 提交于 2019-12-11 01:38:28

问题


In JQuery autocomplete , similar items with difference of multiple spaces in between words are shown as duplicates item in drop-down as Jquery plugin itself is trimming the drop-down items.

Demo:Working demo of issue

var validOptions =["Item 1", "Item        1", "Item     1", "Item 2", "Item   2"];
previousValue = "";

$('#ac').autocomplete({
    autoFocus: true,
    source: validOptions,
}).keyup(function() {
    var isValid = false;
    for (i in validOptions) {
        if (validOptions[i].toLowerCase().match(this.value.toLowerCase())) {
            isValid = true;
        }
    }
    if (!isValid) {
        this.value = previousValue
    } else {
        previousValue = this.value;
    }
});

Is there any way to show the value as such in drop-down items.


回答1:


you need to apply the tiny css for li element white-space: pre-wrap during HTML rendering .

Here is the complete snippet

var validOptions = ["Item 1", "Item        1", "Item     1", "Item 2", "Item   2"];
previousValue = "";

$('#ac').autocomplete({
 autoFocus: true,
 source: validOptions
})
.keyup(function() {
var isValid = false;
for (i in validOptions) {
  if (validOptions[i].toLowerCase().match(this.value.toLowerCase())) {
    isValid = true;
  }
}
if (!isValid) {
  this.value = previousValue
} else {
  previousValue = this.value;
}
}).autocomplete("instance")._renderItem = function(ul, item) {
   return $("<li style='white-space: pre-wrap'>")
  .append(item.label)
  .appendTo(ul);
};

Working fiddle : http://jsfiddle.net/ankurgarg36/kwLmLumd/23/

This .autocomplete("instance")._renderItem function is not working with the your js version. So I need to use latest version suggested here



来源:https://stackoverflow.com/questions/46563371/jquery-autocomplete-not-showing-2-or-multiple-spaces-in-drop-down-suggested

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