jQuery-检索自动完成元素的值 [英] jQuery - retrieve value of autocomplete element
问题描述
我想检索自动完成文本框的值.我尝试使用下面的代码,但是不起作用:
I want to retrieve the value of autocomplete textbox. I tried to use the following code, but it doesn't work:
$('#my_id').bind('result',function(){});
任何建议都会有所帮助.我不想使用.text(),因为它不能满足我的要求.类似于结果"的东西会很好.
Any suggestions will be helpful. I don't want to use .text() as it does not satisfies my requirements. Some thing similar to 'result' will be excellent.
推荐答案
有2个选项.
A)使用事件处理程序选择自动完成的:
A) Use event handler select of autocomplete:
$("#my_id").autocomplete({..., select: function(event, ui){...}});
B)使用事件处理程序自动完成选择:
B) Use event handler autocompleteselect:
$("#my_id").on("autocompleteselect", function(event, ui){...}});
在调试器中,您可以看到两种情况下的事件具有相同的类型autocompleteselect
.两种方法是等效的.如果您希望将所有相关代码放在一个块内,则可以选择A.如果您希望将自动完成列表的填充与所选内容的反应强烈分开,则可以选择B.
In the debugger you can see, that the event in both cases has the same type autocompleteselect
. The both approaches are equivalent. You may choose A, if you prefer to keep all the related code together, within a single block. You may choose B, if you prefer strong separation of filling of the autocompletion list from the reaction on the selection.
A的示例:
在输入字段中输入"a"或"j"以查看其工作原理.
Type 'a' or 'j' in the input field to see how it works.
<!doctype html>
<html lang="en">
<head>
<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>
<script>
$(function() {
var availableItems = [
"ActionScript", "AppleScript", "Groovy", "Java", "JavaScript", "Python", "Scala"
];
$("#my_items").autocomplete({
source: availableItems,
select: function(event, ui) {
alert(
"input: " + event.target.value + "\n" +
"label: " + ui.item.label + "\n" +
"value: " + ui.item.value);
}
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="my_items">Items: </label>
<input id="my_items">
</div>
</body>
</html>
B的示例:
在输入字段中输入"a"或"j"以查看其工作原理.
Type 'a' or 'j' in the input field to see how it works.
<!doctype html>
<html lang="en">
<head>
<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>
<script>
$(function() {
var availableItems = [
"ActionScript", "AppleScript", "Groovy", "Java", "JavaScript", "Python", "Scala"
];
$("#my_items").autocomplete({
source: availableItems
});
$("#my_items").on("autocompleteselect", function(event, ui) {
alert(
"input: " + event.target.value + "\n" +
"label: " + ui.item.label + "\n" +
"value: " + ui.item.value);
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="my_items">Items: </label>
<input id="my_items">
</div>
</body>
</html>
这篇关于jQuery-检索自动完成元素的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!