出於某種原因,我無法獲得用第一個字母進行過濾的文本框,而不是將所有單詞都包含在特定字母中。
以下是我想它的工作的例子:http://jsfiddle.net/miroslav/yLdn3/jQuery自動完成:按首字母過濾
這裏是我的代碼(一切正常,它就會從數據庫表中的地址,但如果我插入「一個」它會給我所有的地址包含「a」,但我想要以「a」開頭的那些)。
getautocomplete.php
<?php
mysql_connect("localhost","username","password");
mysql_select_db("databasename");
$term=$_GET["term"];
$query=mysql_query("SELECT * FROM table where address like '%".$term."%'");
$json=array();
while($table=mysql_fetch_array($query)){
$json[]=array(
'value'=> $table["address"],
'label'=>$table["address"]
);
}
echo json_encode($json);
?>
autocomplete.php
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css"
href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" />
<script type="text/javascript">
$(document).ready(function(){
$("#address").autocomplete({
source:'getautocomplete.php',
});
// Overrides the default autocomplete filter function to search only from the beginning of the string
$.ui.autocomplete.filter = function (array, term) {
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(term), "i");
return $.grep(array, function (value) {
return matcher.test(value.label || value.value || value);
});
};
})();
</script>
</head>
<body>
<form method="post" action="">
Name : <input type="text" id="address" name="address" />
</form>
</body>
<html>
我建議改變你的SQL查詢來返回你想要的,而不是過濾客戶端的數據。 –