出于某种原因,我无法让文本框按首字母进行过滤,而不是给我包含特定字母的所有单词。
这是我希望它如何工作的示例:http://jsfiddle.net/miroslav/yLdn3/
这是我的代码(一切正常,它从数据库表中获取地址,但是如果我插入“a”,它会给我所有包含“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);
?>
自动完成.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>
最佳答案
删除数据库查询中术语前的%
。它的工作方式类似于正则表达式中的 .*
,因此您可以得到类似于 .*term.*
.
关于javascript - jQuery 自动完成 : filter by first letter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23431306/