Okay so I’m using the jQuery autocomplete working with my database of locations and states in the US, the goal is the user starts typing the city, town, etc and I display City (location in my DB), State (region in my DB) Zip (postalCode in my DB) to them and when they select one it fills the city state and zip fields.. My problem is that when I choose an option, the state and zip code fill in correctly, however the city field takes the value of the zip code and I can’t figure it out.. Here is my JS code followed by the separate PHP file that pulls in my DB data.. I’m more experienced in PHP than JS but you never know where you’ll make a mistake…
The JS/jQuery File:
$(document).ready(function(){
var ac_config = {
source: "autocomplete-l.php",
select: function(event, ui){
$("#scity").val(ui.item.location);
$("#sstate").val(ui.item.region);
$("#szip").val(ui.item.postalCode);
},
minLength:1
};
$("#scity").autocomplete(ac_config);
});
And the PHP File:
$cities = array();
$sth = $dbh->prepare("SELECT * FROM locations WHERE country = 'US'");
$sth->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$cities[]=$row;
}
$term = trim(strip_tags($_GET['term']));
$matches = array();
foreach($cities as $city){
if((stripos($city['location'], $term) !== false)){
// Add the necessary "value" and "label" fields and append to result set
$city['value'] = $city['location'];
$city['value'] = $city['region'];
$city['value'] = $city['postalCode'];
$city['label'] = "{$city['location']}, {$city['region']}{$city['postalCode']}";
$matches[] = $city;
}
}
$matches = array_slice($matches, 0, 100);
print json_encode($matches);
call
event.preventDefault();inside the select-function.Otherwise the automplete will proceed with the default-action:
The value will be inserted into the input element
after the user selected something from the menu
The input-element is
$("#scity")and the value is the postal-code:
Note these lines:
…you overwrite
$city['value']you can use only this:
and remove that line from the select-function:
(because $.autocomplete will set the value of
$("#scity")automatically)