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());

代碼到這里就基本結束啦!希望大神們多多指教哈!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM