我正在使用 Autocomplete combobox with Knockout JS template / JQuery 中提供的自定义绑定(bind)
我需要强制要求用户必须在自动完成列表中选择一个值,并且在他们选择该值后无法向选择中添加其他文本。我进行了搜索,但找不到有关如何防止输入其他文本的示例。它必须保持可编辑状态,以防他们选择了错误的下拉菜单,但他们键入的内容必须与列表中的值 100% 匹配。
我找到了 this在 jquery 上发布,但它已经 9 个月大了,没有人发布答案。
最佳答案
没有内置函数可以执行您想要的操作。
我做了一个简单的项目,其中使用了自动完成 change
事件您必须从自动完成中选择值,否则该值将被删除。
变更事件
Triggered when the field is blurred, if the value has changed.
选择后该字段被禁用,您可以使用激活 anchor (例如)激活它。
代码:
$("#artist").autocomplete({
source: function (request, response) {
$.ajax({
url: "http://en.wikipedia.org/w/api.php",
dataType: "jsonp",
data: {
'action': "opensearch",
'format': "json",
'search': request.term
},
success: function (data) {
response(data[1]);
}
});
},
change: function (event, ui) {
if (ui.item == null || ui.item == undefined) {
$("#artist").val("");
$("#artist").attr("disabled", false);
} else {
$("#artist").attr("disabled", true);
}
}
});
$('#changeArtist').click(function (e) {
e.preventDefault();
$("#artist").attr("disabled", false);
});
这是一个 fiddle :http://jsfiddle.net/IrvinDominin/nH4Nx/
关于javascript - jQuery UI 自动完成 : enforce selection from list without modifications,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16379879/