jQuery UI 自动完成:只允许从建议列表中选择值 [英] jQuery UI AutoComplete: Only allow selected valued from suggested list
问题描述
我正在实施 jQuery UI 自动完成,我想知道是否有任何方法可以只允许从返回的 建议结果 中进行选择,而不是允许任何值输入到文本框中.
I am implementing jQuery UI Autocomplete and am wondering if there is any way to only allow a selection from the suggested results that are returned as opposed to allowing any value to be input into the text box.
我将此用于标记系统,与本网站上使用的系统非常相似,因此我只想允许用户从返回到自动完成插件的预填充列表中选择标记.
I am using this for a tagging system much like the one used on this site, so I only want to allow users to select tags from a pre-populated list returned to the autocomplete plugin.
推荐答案
我遇到了同样的问题,选择未定义.找到了解决方法并添加了 toLowerCase
函数,只是为了安全.
I got the same problem with selected not being defined. Got a work-around for it and added the toLowerCase
function, just to be safe.
$('#' + specificInput).autocomplete({
create: function () {
$(this).data('ui-autocomplete')._renderItem = function (ul, item) {
$(ul).addClass('for_' + specificInput); //usefull for multiple autocomplete fields
return $('<li data-id = "' + item.id + '">' + item.value + '</li>').appendTo(ul);
};
},
change:
function( event, ui ){
var selfInput = $(this); //stores the input field
if ( !ui.item ) {
var writtenItem = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val().toLowerCase()) + "$", "i"), valid = false;
$('ul.for_' + specificInput).children("li").each(function() {
if($(this).text().toLowerCase().match(writtenItem)) {
this.selected = valid = true;
selfInput.val($(this).text()); // shows the item's name from the autocomplete
selfInput.next('span').text('(Existing)');
selfInput.data('id', $(this).data('id'));
return false;
}
});
if (!valid) {
selfInput.next('span').text('(New)');
selfInput.data('id', -1);
}
}
}
这篇关于jQuery UI 自动完成:只允许从建议列表中选择值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!