Javascript jQuery UI 自动完成:只允许从建议列表中选择值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4952094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery UI AutoComplete: Only allow selected valued from suggested list
提问by stephen776
I am implementing jQuery UI Autocompleteand am wondering if there is any way to only allow a selection from the suggested resultsthat are returned as opposed to allowing any value to be input into the text box.
我正在实现jQuery UI 自动完成,并且想知道是否有任何方法只允许从返回的建议结果中进行选择,而不是允许将任何值输入到文本框中。
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.
我将它用于标记系统,很像本网站上使用的标记系统,因此我只想允许用户从返回到自动完成插件的预填充列表中选择标记。
采纳答案by Victor
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.
我遇到了同样的问题,选择未定义。为它找到了解决方法并添加了该toLowerCase
功能,只是为了安全。
$('#' + 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);
}
}
}
回答by Jason Gray
You could also use this:
你也可以使用这个:
change: function(event,ui){
$(this).val((ui.item ? ui.item.id : ""));
}
The only drawback I've seen to this is that even if the user enters the full value of an acceptable item, when they move focus from the textfield it will delete the value and they'll have to do it again. The only way they'd be able to enter a value is by selecting it from the list.
我看到的唯一缺点是,即使用户输入了可接受项目的完整值,当他们从文本字段移动焦点时,它将删除该值,并且他们将不得不再次执行此操作。他们能够输入值的唯一方法是从列表中选择它。
Don't know if that matters to you or not.
不知道这对你来说是否重要。
回答by Sam Battat
http://jsfiddle.net/pxfunc/j3AN7/
http://jsfiddle.net/pxfunc/j3AN7/
var validOptions = ["Bold", "Normal", "Default", "100", "200"]
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;
}
});
回答by Matanya
This is how I did it with a list of settlements:
这就是我使用定居点列表的方式:
$("#settlement").autocomplete({
source:settlements,
change: function( event, ui ) {
val = $(this).val();
exists = $.inArray(val,settlements);
if (exists<0) {
$(this).val("");
return false;
}
}
});
回答by Amol Shiledar
i just modify to code in my case & it's working
我只是在我的情况下修改代码并且它正在工作
selectFirst: true,
change: function (event, ui) {
if (ui.item == null){
//here is null if entered value is not match in suggestion list
$(this).val((ui.item ? ui.item.id : ""));
}
}
you can try
你可以试试
回答by pomix
I'm on drupal 7.38 and to only allow input from select-box in autocomplete you only need to delete the user-input at the point, where js does not need it any more - which is the case, as soon as the search-results arrive in the suggestion-popup right there you can savely set:
我在 drupal 7.38 并且只允许从自动完成中的选择框输入你只需要删除用户输入点,js 不再需要它 - 在这种情况下,只要搜索 -结果出现在建议弹出窗口中,您可以保存设置:
**this.input.value = ''**
see below in the extract from autocomplete.js ... So I copied the whole Drupal.jsAC.prototype.found object into my custom module and added it to the desired form with
请参阅下面 autocomplete.js 的摘录...所以我将整个 Drupal.jsAC.prototype.found 对象复制到我的自定义模块中,并将其添加到所需的表单中
$form['#attached']['js'][] = array(
'type' => 'file',
'data' => 'sites/all/modules/<modulname>_autocomplete.js',
);
And here's the extract from drupal's original misc/autocomplete.js modified by that single line...
这是由那一行修改的 Drupal 原始 misc/autocomplete.js 的摘录......
Drupal.jsAC.prototype.found = function (matches) {
// If no value in the textfield, do not show the popup.
if (!this.input.value.length) {
return false;
}
// === just added one single line below ===
this.input.value = '';
// Prepare matches.
=cut. . . . . .
=切。. . . . .
回答by Daniel Forrest
Ajax submission and handling
Ajax 提交和处理
This will be of use to some of you out there:
这对你们中的一些人有用:
$('#INPUT_ID').autocomplete({
source: function (request, response) {
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: autocompleteURL,
data: "{'data':'" + $('INPUT_ID').val() + "'}",
dataType: 'json',
success: function (data) {
response(data.d);
},
error: function (data) {
console.log('No match.')
}
});
},
change: function (event, ui) {
var opt = $(this).val();
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: autocompleteURL,
data: "{'empName':'" + name + "'}",
dataType: 'json',
success: function (data) {
if (data.d.length == 0) {
$('#INPUT_ID').val('');
alert('Option must be selected from the list.');
} else if (data.d[0] != opt) {
$('#INPUT_ID').val('');
alert('Option must be selected from the list.');
}
},
error: function (data) {
$(this).val('');
console.log('Error retrieving options.');
}
});
}
});
回答by user7793758
If you would like to restrict the user to picking a recommendation from the autocomplete list, try defining the close function like this. The close function is called when the results drop down closes, if the user selected from the list, then event.currentTarget is defined, if not, then the results drop down closed without the user selecting an option. If they do not select an option, then I reset the input to blank.
如果您想限制用户从自动完成列表中选择推荐,请尝试像这样定义关闭函数。当结果下拉关闭时调用 close 函数,如果用户从列表中选择,则 event.currentTarget 被定义,如果没有,则结果下拉关闭,用户不选择选项。如果他们没有选择一个选项,那么我将输入重置为空白。
//
// Extend Autocomplete
//
$.widget( "ui.autocomplete", $.ui.autocomplete, {
options: {
close: function( event, ui ) {
if (typeof event.currentTarget == 'undefined') {
$(this).val("");
}
}
}
});