jQuery AutoComplete results to something besides textboxes?
Okay, I have been messing with this autocomplete stuff for 2 weeks now, and it's starting to give me a headache! I've gotten it to do almost everything I need, but I'm hung up on one issue. I have two autocomp开发者_C百科lete text inputs that are tied together. The first input allows the user to select a person from a MySQL database table. Then, based on that selection, the second input allows the user to select one of the person's addresses from an addresses database table. This part all works fine.
The problematic autocomplete field queries an addresses table and stores each result in an array slot as follows:
title|street_address|city|state|zip
The trouble comes when simply trying to output the selected item's data to the innerHTML of a SPAN tag.
I've used the formatItem option to only display the title in the autocomplete list. Upon selecting the item I want it to then show the street_address, city, state and zip in a SPAN tag below the input box. It's getting the information, but since the formatItem function automatically reads through every row, it is displaying the street_address, city, state and zip of the last item in the list instead of the one that is selected. However, what is returned to the text input is the title of the selected item. It's very frustrating!
Does anyone know how I can get this issue sorted out???
Thanks in advance for any help!
I'm assuming you're using http://code.google.com/p/jquery-autocomplete/ or one of the variants. What you need to do is attach an event to onItemSelect. In older versions you'd get the LI element and an optional extra array of data. In the most recent version (after the rewrite), you get the standard value and optional data response. If you're confused, just start out with this setting (assuming Firebug or othe provider of console.log):
...
onItemSelect = function(a, b) { console.log(a); console.log(b); }
...
This will show you the response of the version you are using. You can work from there.
Let me know if you can get it to work. If you run into problems, I'll write a more complete example.
DEMO
JS code:
$(function() {
var houses = [
{
title: "House 1",
value: "House 1",
street_address: "Address 1",
city: "City 1",
state:"State 1",
zip:123456
},
{
title: "House 2",
value: "House 2",
street_address: "Address 2",
city: "City 2",
state:"State 2",
zip:456123
}
];
$( "#house" ).autocomplete({
minLength: 0,
source: houses,
/*focus: function( event, ui ) {
$( "#project" ).val( ui.item.label);
return false;
},*/
select: function( event, ui ) {
$('#house_address').html(ui.item.street_address+", "+ui.item.city+", "+ui.item.state+", "+ui.item.zip);
return false;
}
})
});
HTML:
<div id="project-label">Select a house(type like "h" for a start):</div>
<input type="text" id="house">
<br>
House complete address:<br>
<span id="house_address"></span>
精彩评论