I have the following jquery Autocomplete form that pulls data in from a local XML file.
It works fine and displays the data as it should, but how can I return a specific data value into the search field?
For example, when searching for London, the auto complete returns values thus:
London Heathrow Airport, UK –
Which is great – BUT I’d like it populate the actual search field by grabbing a specific XML ID, (The airport code = IATA) and add ONLY that to the search field – like this:
LHR
How can I achieve that ?
Here’s the jquery code
@Nicola Peluchetti
Thanks for your help and answer – this is what I got from your comments – but it’s not working – did I miss something ?
$(document).ready(function() {
var myArr = [];
$.ajax({
type: "GET",
url: "airports.xml",
dataType: "xml",
success: parseXml,
complete: setupAC,
failure: function(data) {
alert("XML File could not be found");
}
});
function parseXml(xml)
{
//find every query value
$(xml).find("state").each(function()
{
//you are going to create an array of objects
var thisItem = {};
var thisItem[label] = $(this).attr("label") + ', ' + $(this).attr("country");
var thisItem[value] = $(this).attr("iata");
myArr.push(thisItem);
});
}
function setupAC() {
$("#city").autocomplete({
source: myArr,
minLength: 3,
select: function(event, ui) {
//replace the label with the value
$(this).val(ui.value);
}
});
}
});
and here’s the airports.xml file snippet
<states>
<state label="London Heathrow" iata="LHR" country="UK" />
<state label="Syndey" iata="SYD" country="Australia" />
….
And the search form snippet
<label for="city">From</label></td>
EDIT (i modified the answer according to the comments) – You could modify this function:
EDIT 2 – you don’t need this second part: autocomplete automatically replace the “label” with the “value” if you specify both of them in the object
semplified fiddle here : http://jsfiddle.net/7cLxD/1/