我正在使用jquery自动完成插件。一切运行正常,但是如果下拉列表中只有一项,我就会触发select函数,以便自动填充字段。 基本上这些都是在页面加载后进行设置的。
这是我做的一个示例:$('#auto-complete').autocomplete({
source:function(){//get data here},
select:function(e,ui){
//setting fields here:
$('#user').val("");
},
focus:function(){}
});
我已经添加了响应功能,但即使这样,似乎也需要先在自动完成字段中进行更改。
You can use the Response
callback:
Triggered after a search completes, before the menu is shown. Useful for local manipulation of suggestion data, where a custom
source
option callback is not required. This event is always triggered when a search completes, even if the menu will not be shown because there are no results or the Autocomplete is disabled.
Source: https://api.jqueryui.com/autocomplete/#event-response
$(function() {
/*
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
*/
var availableTags = [
"ActionScript"
];
$("#tags").autocomplete({
source: availableTags,
minLength: 0,
response: function(e, ui) {
if (ui.content.length == 1) {
$(this).val(ui.content[0].value);
$(this).autocomplete("close");
}
}
});
$("#tags").autocomplete("search", "");
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
This is helpful is testing the the results after your Custom Source is called. I suspect you will need to update it a bit.
Alternately, you can test the results before you send the results to response()
and if they are only 1, set the value
at that time.
</div>