Reputation: 55
For some reason I can't get a text box to filter by first letters, rather than giving me all the words than contain a particular letter.
Here's an example how I'd like it to work: http://jsfiddle.net/miroslav/yLdn3/
And here's my code (everything works, it gets the address from the database table, but if I insert "a" it will give me all the addresses that contain "a", but I want the ones that start with "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>
Upvotes: 0
Views: 1631
Reputation: 3
try to use this query :
SELECT * FROM table where substr(address,1,1) like '%".$term."%'"
Upvotes: 0
Reputation: 13562
Remove %
before the term in your database query. It works like .*
in regexp so you have something like .*term.*
.
Upvotes: 1