问题描述
我在一个输入字段上使用自动完成功能来填写另一个字段:
I'm using autocomplete on one input field to fill in another:
<input id='fruit' name='fruit' type='text'>
<input id='details' name='details' type='text'>
jQuery代码:
var x = ["apple", "kiwi", "lemon"];
$( "#fruit" ).autocomplete({
source: x
});
jQuery(document).on("change","#fruit", function()
{
$.each(x, function(key, value) {
switch(value) {
case "apple":
$('#details').val("Delicious");
break;
case "kiwi":
$('#details').val("Yummy");
break;
case "lemon":
$('#details').val("Sour");
}
});
});
当某人选择具有自动完成功能的苹果,猕猴桃或柠檬时,它将用相应的文本填充另一个输入字段.
When someone selects apple, kiwi or lemon with the autocomplete then it fills out the other input field with the corresponding text.
我有两个问题:
- 当前,它总是打印出酸味"
- 当您从自动完成功能中选择一个条目时,您必须再次单击以填写该字段.当有人从自动完成功能中选择一个选项时,有没有办法做到这一点?
这里是 小提琴
Here is a fiddle
推荐答案
我想您使用switch会遇到一些困难.如果查看ui文档,您会发现可以使用对象数组.如果我是你,我会把这样的来源:
I guess you get things bit hard using switch. If you take a look over ui documentaton you will see that you can use array of objects. If i were you i would put the source like this :
var x = [
{ label : 'apple', value : 'Delicious' },
{ label : 'kiwi', value : 'Yummy' },
{ label : 'kiwiooo', value : 'aaa' },
{ label : 'lemon', value : 'Sour' }
];
现在,您知道对于某个标签,您具有一定的值,而无需使用switch和其他内容,因此其余代码看起来像
Now you know that for a certain label you have a certain value, without using switch and other stuff, so the rest of code will looks like
$( "#fruit" ).autocomplete({
source: x,
focus : function(){ return false; }
})
.on( 'autocompleteresponse autocompleteselect', function( e, ui ){
var t = $(this),
details = $('#details'),
label = ( e.type == 'autocompleteresponse' ? ui.content[0].label : ui.item.label ),
value = ( e.type == 'autocompleteresponse' ? ui.content[0].value : ui.item.value );
t.val( label );
details.val( value );
return false;
});
我在focus
上放置return false,因为如果用户选择使用键盘箭头在列表上向下滑动,则在#fruit
中输入将出现该值,这不是确定的.
I put return false on focus
because if the user choose to slide down on list with keyboard arrows, in #fruit
input will appear the value and this is not ok.
您可以在此处
这篇关于jQuery自动完成功能以填写其他字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!