如何在自动完成文本框jquery中使用数组? [英] How to use array in autocomplete textbox jquery?
问题描述
例如
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
var availableTags = [ "ActionScript", "AppleScript", "Asp"];
var availableTagsCode = ["1", "2", "3"];
$( "#tags" ).autocomplete({ source: availableTags });
});
</script>
<input id="tags" name="name">
<input id="tags_code" name="code">
实际上,我尝试使用以下代码选择建议时更改代码:
Actually, I have tried to change code while select suggestion using following code:
$("#tags_code").val(availableTagsCode);
如果我选择 0 $ c,我需要选择建议测试$ c>来自标签的数组
0
代码应分配给 name =code
textbox。
请帮我解决这个问题。
I need to select suggestion test if i will select 0
th array from tag the 0
th code should assign to name="code"
textbox.
Please help me to resolve this problem.
推荐答案
你可以定义选择
事件处理程序:
You can define a select
event handler:
$( "#tags" ).autocomplete({
source: availableTags,
select: function(event, ui) {
var index = availableTags.indexOf(ui.item.value);
$("#tags_code").val(availableTagsCode[index]);
}
});
这是工作JSFiddle演示。
实际上,jQuery UI允许你使用 value <的对象数组当您提供
source
时,/ code>和标签
属性。
所以,某事这样会更好看:
Actually, jQuery UI allows you to use an array of objects with value
and label
properties when you provide source
.
So, something like this will work and look better:
var tags = [
{"label": "ActionScript", "value": 1},
{"label": "AppleScript", "value": 2},
{"label": "Asp", "value": 3}
];
$( "#tags" ).autocomplete({
source: tags,
select: function (event, ui) {
$("#tags_code").val(ui.item.value);
}
});
如果您不希望在选择后替换该值,则可以使用自定义属性而不是 value
:
If you don't want the value to be replaced after choosing, you can use custom property instead of value
:
var tags = [
{"label": "ActionScript", "code": 1},
{"label": "AppleScript", "code": 2},
{"label": "Asp", "code": 3}
];
$( "#tags" ).autocomplete({
source: tags,
select: function (event, ui) {
$("#tags_code").val(ui.item.code);
}
});
这篇关于如何在自动完成文本框jquery中使用数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!