因为jQuery UI - v1.11.0
我不得不改变一点Scott González 的 autoSelect 扩展,如下所示。
/*
* jQuery UI Autocomplete Auto Select Extension
*
* Copyright 2010, Scott González (http://scottgonzalez.com)
* Dual licensed under the MIT or GPL Version 2 licenses.
*
* http://github.com/scottgonzalez/jquery-ui-extensions
*/
$().ready(function () {
$.ui.autocomplete.prototype.options.autoSelect = true;
$(".ui-autocomplete-input").change(function (event) {
var autocomplete = $(this).data("uiAutocomplete");
if (!autocomplete.options.autoSelect || autocomplete.selectedItem) { return; }
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i");
autocomplete.widget().children(".ui-menu-item").each(function () {
var item = $(this).data("uiAutocompleteItem");
if (matcher.test(item.label || item.value || item)) {
autocomplete.selectedItem = item;
return false;
}
});
if (autocomplete.selectedItem) {
autocomplete._trigger("select", event, { item: autocomplete.selectedItem });
}
});
});
autoSelect: true
并且必须在我的自动完成定义中应用扩展的自动完成选项。
我从这些答案中提取了一些代码。
- 特鲁什凯维奇
- 格多伦和
- 卡加泰卡兰
编辑
这是我的自动完成定义,以防有人感兴趣。
$("your selector").autocomplete({
// Below filter looks for the values that start with the passed in string
source: function (request, response) {
var matches = $.map(yourSourceArray, function (acItem) {
if (acItem.toUpperCase().indexOf(request.term.toUpperCase()) === 0) {
return acItem;
}
});
response(matches);
},
// one can directly pass the source array instead like,
// source: yourSourceArray
autoSelect: true,
autoFocus: true,
minLength: 3,
change: function (event, ui) {
if (ui.item) {
// do whatever you want to when the item is found
}
else {
// do whatever you want to when the item is not found
}
}
})