Reputation: 5800
The below code is working fine to autocomplete the location but how can I make when I click on the list it will fill the other 2 textboxes with latitude and longitude?
PHP
$pdo = connect();
$keyword = '%'.$_POST['keyword'].'%';
$sql = "SELECT * FROM locations WHERE location LIKE (:keyword) AND state='QLD' AND latitude !=0 AND longitude !=0 ORDER BY postcode ASC LIMIT 0, 10";
$query = $pdo->prepare($sql);
$query->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$query->execute();
$list = $query->fetchAll();
foreach ($list as $rs) {
$country_name = str_replace($_POST['keyword'], '<b>'.$_POST['keyword'].'</b>', $rs['location']. ' ' .$rs['state']. ' ' .$rs['postcode']);
echo '<li onclick="set_item(\''.str_replace("'", "\'", $rs['location']).'\')">'.$country_name.'</li>';
}
HTML
<input type="text" id="country_id" onkeyup="autocomplet()">
<input type="text" id="latitude">
<input type="text" id="longitude">
<ul id="country_list_id"></ul>
JavaScript
function autocomplet() {
var min_length = 0;
var keyword = $('#country_id').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'ajax_refresh.php',
type: 'POST',
data: {keyword:keyword},
//data2: {keyword2:keyword2},
success:function(data){
$('#country_list_id').show();
$('#country_list_id').html(data);
//$('#latitude').html(data2);
}
});
} else {
$('#country_list_id').hide();
}
}
function set_item(item) {
$('#country_id').val(item);
$('#country_list_id').hide();
}
Upvotes: 0
Views: 287
Reputation: 1152
If you click on li, item should be "LAT,LNG" right ? Then your function should look like
function set_item(item) {
var coordinates = item.split(",");
$('#latitude').val(coordinates[0]);
$('#longitude').val(coordinates[1]);
$('#country_id').val(item);
$('#country_list_id').hide();
}
Upvotes: 1
Reputation: 121
If you have latitude and longitude on the server: Return the latitude and longitude with the server response and bind them to the autocomplete items as data attributes.
On selection, use these values to populate the other inputs.
An alternative method would be to do this client side using google geocode JS api, which has no limits for client side implementations. This could be done onclick and is async so you would need a callback that inserted the returned information.
Edit:
So your output would look like
echo '<li onclick="set_item(\''.str_replace("'", "\'", $rs['location']).'\')" data-lat="<?php echo $lat; ?>" data-lng="<?php echo $lng; ?>">'.$country_name.'</li>';
And in set_item() function you would need something like
var $this = $(this),
lng = $this.data('lng'),
lat = $this.data('lat');
$('#lat').val(lat);
$('#lng').val(lng);
if you are using jQuery^
Upvotes: 1