PHP and jQuery Autocomplete example

HTML and Javascript
--------------------------------------------------------------------------------------------------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type='text/javascript' src='jquery.autocomplete.js'></script>
<link rel="stylesheet" type="text/css" href="jquery.autocomplete.css" />
<script type="text/javascript">

function lookupAjax(){
var oSuggest = $("#CityAjax")[0].autocompleter;
oSuggest.findValue();
return false;
}
$(document).ready(function() {
$("#CityAjax").autocomplete(
"getData.php",
{
delay:10,
minChars:2,
matchSubset:1,
matchContains:1,
cacheLength:10,
onItemSelect:selectItem,
onFindValue:findValue,
formatItem:formatItem,
autoFill:true
}
);
});
function findValue(li) {
if( li == null ) return alert("No match!");
// if coming from an AJAX call, let's use the CityId as the value
if( !!li.extra ) var sValue = li.extra[0];
// otherwise, let's just display the value in the text box
else var sValue = li.selectValue;
//alert("The value you selected was: " + sValue);
}
function formatItem(row) {
return row[0] + " (id: " + row[1] + ")";
}
function selectItem(li) {
findValue(li);
}
</script>
</head>
<body>
<input type="text" id="CityAjax" value="" style="width: 200px;" />
<input type="button" value="Get Value" onclick="lookupAjax();" />
</body>
</html>

--------------------------------------------------------------------------------------------------------------


PHP
--------------------------------------------------------------------------------------------------------------
$name = strtolower($_GET['q']).'%';

$sql = "SELECT * FROM clubs WHERE lower(name) LIKE ".$name." ORDER BY name ASC";
$r = db_query($sql);
while($x = db_fetch($r)){
print $x['name']."\n";
}
--------------------------------------------------------------------------------------------------------------

reference
http://www.pengoworks.com/workshop/jquery/autocomplete.htm

沒有留言: