javascript - jQuery 自动完成 : filter by first letter

标签 javascript php jquery regex

出于某种原因,我无法让文本框按首字母进行过滤,而不是给我包含特定字母的所有单词。
这是我希望它如何工作的示例: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/

相关文章:

javascript - D3 从 csv 填充数据集失败

javascript - 主体未定义

javascript - 具有多个系列的 Highcharts 异步服务器加载

javascript - 如何在 JavaScript 中为 setInterval() 设置自定义时间?

javascript - 在 node.js 中优雅地重启

javascript - 如何通过 socket.io 将图像发送到服务器?

php - 我怎样才能用 JavaScript 编写这个 PHP 代码

javascript - 不允许在文本区域上使用 "@"

php - 启用 PHP 对 Windows 中文件夹的访问

javascript - 将数据存储在模型中并从 Collection 和 Fetch 中调用