Retrieving data from mySql is a simple task, but once I have the list of items, I've been struggling to create a function that allows clicking on any item in the list to send the text up to the value of the input field. Here's what I've come up with after several days of effort.
// Function to request city data
function searchCities(str) {
var responses = document.getElementById('suggestions');
if (str.length == 0) {
responses.innerHTML = "";
responses.setAttribute("style", "display:none;border:none;outline:none;");
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
responses.innerHTML = this.responseText;
responses.setAttribute("style","display: block;border-top: 1px solid #272C33;border-radius: 0 0 4px 4px;padding: 10px;");
}
};
xmlhttp.open("GET", "/editor/queries/cities.php?city=" + str, true);
xmlhttp.send();
}
}
// Attempting to send the content to an input field
var items = document.querySelectorAll("#suggestions li");
for(var i = 0; i < items.length; i++ )
{
items[i].onclick = function(){
document.getElementById('inputField').value = this.innerHTML;
};
}
This involves two html elements in the dynamic process:
<input type="search" class="searchBox" name="city" id="inputField" placeholder="Enter destination name" onkeyup="searchCities(this.value)" for="suggestions">
<ul id="suggestions" class="suggestions">
</ul>
Here is the structure of the query:
$city = htmlentities( $_GET['city'], ENT_COMPAT, 'UTF-8' );
$query = $dcon
->query( "
SELECT *
FROM cities
WHERE city LIKE '%$city%'
ORDER BY city
ASC LIMIT 10" );
while ( $result = $query->fetch() )
{
echo $cityOutput = '<li>' . $result['city'] . ', ' . $result['state']. ", " . $result['country'] . '</li>';
}
Could it be that the function isn't working because it requires a pre-existing list to load? And if so... HOW?