dongpi3237 2014-05-02 15:07
浏览 43

jQuery自动完成:按首字母过滤

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>
  • 写回答

2条回答 默认 最新

  • doupingtang9627 2014-05-02 15:11
    关注

    Remove % before the term in your database query. It works like .* in regexp so you have something like .*term.*.

    评论

报告相同问题?

悬赏问题

  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害