问题
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 code:
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.
I have two issues:
- Currently it always prints out "Sour"
- When you select an entry from the autocomplete you have to click away again to fill out the field. Is there a way to do this when someone selects a choice from autocomplete?
Here is a fiddle
回答1:
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' }
];
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;
});
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.
You can play with stuff right here
回答2:
You don't need or want the each loop inside the change handler. Just use the value of your input.
$(document).on("change","#fruit", function()
{
switch($('#fruit').val()) {
case "apple":
$('#details').val("Delicious");
break;
case "kiwi":
$('#details').val("Yummy");
break;
case "lemon":
$('#details').val("Sour");
}
});
This code could be improved by not performing the $('#fruit')
on each invocation of the handler, but it'll solve your problem.
回答3:
You can use autocomplete's change:
$('#fruits').autoceomplete({ source: x,
change: function (event, ui) {
switch(ui.item){
case 'apple': break;
case 'kiwi': break;
}
}})
来源:https://stackoverflow.com/questions/17201730/jquery-autocomplete-to-fill-in-another-field