jQuery-AutoComplete自动提示简单实现

注:本次案列实现功能为 用户注册信息,如果数据库对应表中存在部分信息,点击已有的用户的用户名,自动补全其它已有的基本信息

实现思路:通过AutoComplete提示,异步通过用户名查询全表,充当AutoComplete数据源source , 当点击文本框输入用户名前一个字时,把从数据库中匹配到的用户名绑定到下拉框中,当点击下拉框中的用户名时,自动补全其它信息

1:首先引入需要的文件:两个js文件,两个css文件 如下:

<link rel="stylesheet" href="//apps.bdimg.com/libs/jqueryui/1.10.4/css/jquery-ui.min.css">

<script src="//apps.bdimg.com/libs/jquery/1.10.2/jquery.min.js"></script>

<script src="//apps.bdimg.com/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>

<link rel="stylesheet" href="jqueryui/style.css">

前段html代码:

<form id="form1" runat="server">
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>  用户名
         <br />
        <asp:TextBox ID="txtPhone" runat="server"></asp:TextBox>  电话
        <br />
        <asp:TextBox ID="txtAdd" runat="server"></asp:TextBox>   家庭住址
 </form>

JavaScript代码:

<script>
        $(function () {
            $("#txtName").autocomplete({  //用户名
                minLength: 0,
                source: "Handler.ashx",  异步查出的全表数据充当数据源
                focus: function (event, ui) {      focus为焦点事件
                    $("#txtName").val(ui.item.UserName + " " + ui.item.Phone);   //因为数据库中会有重名的 所有在这里我把用户名和电话一起绑出
                    return false
                },
                select: function (event, ui) {    select为: 下拉框点击事件
                    $("#txtName").val(ui.item.UserName);   给用户名文本框赋值
                    $("#txtPhone").val(ui.item.Phone);  电话文本框赋值
                    $("#txtAdd").val(ui.item.Add);   家庭地址赋值
                    return false;
                }
            })
            .data("ui-autocomplete")._renderItem = function (ul, item) {   拼出的li标签为样式
                return $("<li>")
                  .append("<a>" + item.UserName + " " + item.Phone + "</a>")
                  .appendTo(ul);
            };
        });
    </script>

异步C#代码:

 string querystring = context.Request["term"].ToString();  term为参数名  这个参数可以通过谷歌浏览器开发者查看,默认的参数,刚加载参数为空查询全表,当你点击用户名时候,team对应的值就是你点击的内容,接收到你点击的内容,去数据库中模糊查询
        StringBuilder str = new StringBuilder();
        DataSet ds = KangHui.BaseClass.DbHelperSQL.Query("select * from dbo.Users where UserName Like '%"+querystring+"%'", KangHui.Common.ConfigHelper.GetConnectionString("sqlconn"));
拼JSON串 if (ds.Tables[0].Rows.Count > 0) { str.Append("["); for (int i = 0; i
< ds.Tables[0].Rows.Count; i++) { str.Append("{\"Phone\":\"" + ds.Tables[0].Rows[i]["Phone"] + "\",\"UserName\":\"" + ds.Tables[0].Rows[i]["UserName"] + "\",\"Age\":\"" + ds.Tables[0].Rows[i]["Age"] + "\"},"); } str.Remove(str.Length - 1, 1); str.Append("]"); } context.Response.Write(str.ToString());

代码到这里就基本结束啦!希望大神们多多指教哈!

posted @ 2019-01-11 14:01  初晨~  阅读(1205)  评论(0编辑  收藏  举报