I thought i would write this tutorial because most of the auto completer applications i have seen just dump the code into a zip and tell you how to use it rather than how and why it works, knowing about this enables you to customise it a lot more (this has been demonstrated with the other apps i have written here)!
<script src="jquery-1.2.1.pack.js" type="text/javascript"></script>
<script type="text/javascript">
function lookup(inputString) {
if(inputString.length == 0) {
// Hide the suggestion box.
$('#suggestions').hide();
} else {
$.post("rpc.php", {queryString: ""+inputString+""}, function(data){
if(data.length >0) {
$('#suggestions').show();
$('#autoSuggestionsList').html(data);
}
});
}
} // lookup
function fill(thisValue) {
$('#inputString').val(thisValue);
$('#suggestions').hide();
}
</script>
Now for the PHP Backend (RPC.php)
As always my PHP Backend page is called rpc.php (Remote Procedure Call) not that it actually does that, but hey-ho.
<?
include("common.inc");
if(isset($_POST['queryString'])) {
$queryString = $_POST['queryString'];
if(strlen($queryString) >0) {
$query = "SELECT blog_tags FROM blog_entry WHERE blog_tags LIKE '$queryString%' LIMIT 10";
$result = mysql_query($query) or die("There is an error in database please contact support@ExploreMyBlog.Com");
while($row = mysql_fetch_array($result)){
echo '<li onClick="fill(''.$row[blog_tags].'');">'.$row[blog_tags].'</li>';
}
}
}
?>
CSS Styling - im using CSS3, YEA BABY! much easier although limits the functionality to Firefox and Safari.
<style type="text/css">
.suggestionsBox {
position: relative;
left: 30px;
margin: 10px 0px 0px 0px;
width: 200px;
background-color: #212427;
-moz-border-radius: 7px;
-webkit-border-radius: 7px;
border: 2px solid #000;
color: #fff;
}
.suggestionList {
margin: 0px;
padding: 0px;
}
.suggestionList li {
margin: 0px 0px 3px 0px;
padding: 3px;
cursor: pointer;
}
.suggestionList li:hover {
background-color: #659CD8;
}
</style>
The CSS is pretty standard, nothing out of the ordinary.
Main HTML
<div>
<div>
Type your county (for the demo):
<input size="30" id="inputString" onkeyup="lookup(this.value);" type="text" />
</div> <div class="suggestionsBox" id="suggestions" style="display: none;">
<img src="upArrow.png" style="position: relative; top: -12px; left: 30px" alt="upArrow" />
<div class="suggestionList" id="autoSuggestionsList">
</div>
</div>
</div>
VIEW DEMO
DOWNLOAD CODE