【发布时间】:2011-02-25 09:32:24
【问题描述】:
这是我目前拥有的,不幸的是我似乎无法弄清楚如何让autoFill 与 jQuery-UI 一起使用...它曾经与直接的 Autocomplete.js 一起使用
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js" type="text/javascript"></script>
<script src="http://jquery-ui.googlecode.com/svn/tags/latest/external/jquery.bgiframe-2.1.1.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/i18n/jquery-ui-i18n.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
var thesource = "RegionsAutoComplete.axd?PID=3"
$(function () {
function log(message) {
$("<div/>").text(message).prependTo("#log");
$("#log").attr("scrollTop", 0);
}
$.expr[':'].textEquals = function (a, i, m) {
return $(a).text().match("^" + m[3] + "$");
};
$("#regions").autocomplete({
source: thesource,
change: function (event, ui) {
//if the value of the textbox does not match a suggestion, clear its value
if ($(".ui-autocomplete li:textEquals('" + $(this).val() + "')").size() == 0) {
$(this).val('');
}
else {
//THIS IS CURRENTLY NOT "LOGGING" THE "UI" DATA
//IF THE USER DOES NOT EXPLICITLY SELECT
//THE SUGGESTED TEXT
//PLEASE HELP!!!
log(ui.item ? ("Selected: " + ui.item.value + " aka " + ui.item.id) : "Nothing selected, input was " + this.value);
}
}
}).live('keydown', function (e) {
var keyCode = e.keyCode || e.which;
//if TAB or RETURN is pressed and the text in the textbox does not match a suggestion, set the value of the textbox to the text of the first suggestion
if ((keyCode == 9 || keyCode == 13) && ($(".ui-autocomplete li:textEquals('" + $(this).val() + "')").size() == 0)) {
$(this).val($(".ui-autocomplete li:visible:first").text());
}
});
});
</script>
我在后端的 JSON 是这样的
[
{ "label": "Canada", "value": "Canada", "id": "1" },
{ "label": "United States", "value": "United States", "id": "2" },
]
我已使用答案 here 来使 mustMatch 正常工作,但不幸的是,如果我从输入框“tab”离开,或者我完全键入单词而不是实际选择建议的文本,我会得到“Nothing” selected" 响应而不是值和 ID。
有谁知道当您没有实际选择字段时如何从自动完成中提取 id?
基本上,我正在寻找的是类似于在此处找到的 Month (local): 示例:http://jquery.bassistance.de/autocomplete/demo/
但显然使用 jQuery-UI 而不是 jquery.autocomplete.js
【问题讨论】:
-
恕我直言来自 bassistance.de 的人做得很好,你为什么要重新发明井!?如果你使用 jQuery UI 但取消选择 Autocomple 组件并使用来自 bassistance.de 的组件,你会做得更好 - jQuery UI Autocomplete 7.45 KB minified - jQuery plugin: Autocomplete 13.7 KB 缩小
-
这是一个很好的观点,但来自 bassistance.de 的那个不在我能找到的任何 CDN 中。他们说 dev.jquery.com 上的那个将被取消以支持 jQuery-UI
-
旁注:尽量避免在 JavaScript 对象和数组中出现尾随逗号。有些浏览器不能正确处理它们。
-
我更新了 jQuery-UI 组合框演示以支持自动填充。在此评论中查看我的答案:stackoverflow.com/questions/2587378/…
标签: jquery json jquery-ui jquery-validate autofill