天天看點

Asp.net文本框輸入提示功能(jquery-autocomplete)

上一篇文章講解了jquery-ui實作文本框輸入提示功能的做法,後來又發現了一個挺好用的能實作文本框輸入提示功能的jquery插件jquery-autocomplete,這次講一下他的用法。

Asp.net文本框輸入提示功能(jquery-autocomplete)

引入所需檔案

<script type="text/javascript" src="JS/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="JS/jquery.autocomplete.min.js"></script>
<link href="CSS/jquery.autocomplete.css" target="_blank" rel="external nofollow"  rel="stylesheet" />
           

動态單屬性資料源

前台代碼:

$(document).ready(function () {            
    $("#txtAutoComplete").autocomplete("AutoComplete.ashx", {
        max: 10,             //清單裡的條目數
        minChars: 1,         //自動完成激活之前填入的最少字元
        scrollWidth: 173,    //提示的寬度,溢出隐藏
        scrollHeight: 200,   //提示的高度,溢出顯示滾動條
        scroll: true,        //是否顯示滾動條
        matchContains: true, //包含比對,是否隻顯示比對項
        autoFill: false,     //自動填充
        //此處實際請求的URL為"AutoComplete.ashx?q='[你在txtAutoComplete中輸入的值]'&action='autoComplete'&value='guo'"
        extraParams: { action: "autoComplete", value: "guo" },
        //格式化清單中的條目 row:條目對象,i:目前條目index,max:總條目數
        formatItem: function (row, i, max) {
            //【不用轉化為js對象,但必須傳回row.toString()】
            return row.toString();
        },
        //配合formatItem使用,作用在于,由于使用了formatItem,是以顯示的條目内容有所改變,
        //而我們要比對的是原始的資料,是以用formatMatch做一個調整,使之比對原始資料
        formatMatch: function (row, i, max) {
            //【不用轉化為js對象,但必須傳回row.toString()】            
            return row.toString();
        },
        //設定使用者選擇某一條目後文本框顯示的内容
        formatResult: function (row) {
            //【不用轉化為js對象,但必須傳回row.toString()】
            return "文本框顯示的結果:" + row.toString();
        }
    }).result(function (event, row, formatted) {
        //擷取使用者選擇的條目
        alert(row.toString());
    });
});
<body>
    <form id="form1" runat="server">
        請輸入:<input type="text" id="txtAutoComplete" />
    </form>
</body>
           

AutoComplete.ashx背景代碼:

public class AutoComplete : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        //text表示使用者在文本框輸入的内容
        string text = context.Request.QueryString["q"];
        string action = context.Request.QueryString["action"];
        string value = context.Request.QueryString["value"];
        <!--各項之間必須用"\n"隔開,不能用","隔開-->
        string strResult = "guo\ntong\nchang\nwang\nhao\nbang";
        context.Response.Write(strResult);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}
           

動态多屬性資料源

前台代碼:

$(document).ready(function () {               
    $("#txtAutoComplete").autocomplete("AutoComplete.ashx", {
        max: 10,             //清單裡的條目數
        minChars: 1,         //自動完成激活之前填入的最少字元
        width: 173,          //提示的寬度,溢出隐藏
        scrollHeight: 200,   //提示的高度,溢出顯示滾動條
        scroll: true,        //是否顯示滾動條
        matchContains: true, //包含比對,是否隻顯示比對項
        autoFill: false,     //自動填充
        //此處實際請求的URL為"AutoComplete.ashx?q='[你在txtAutoComplete中輸入的值]'&action='autoComplete'&value='guo'"
        extraParams: { action: "autoComplete", value: "guo" }, 
        //格式化清單中的條目,使其以自定義格式顯示 
        //row:條目對象,i:目前條目index,max:總條目數
        formatItem: function (row, i, max) {
            //轉換成js對象 【不同點1】
            var obj = eval('(' + row + ')'); 
            return i + "/" + max + ": " + obj.key + obj.value;
        },
        //配合formatItem使用,作用在于,由于使用了formatItem,是以顯示的條目内容有所改變,
        //而我們要比對的是原始的資料,是以用formatMatch做一個調整,使之比對原始資料
        formatMatch: function (row, i, max) {
            //轉換成js對象
            //擷取對象中的某一屬性時,名稱嚴格區分大小寫
            var obj = eval('(' + row + ')'); 
            return "Match:" + obj.key + row.value;
        },
        //設定使用者選擇某一條目後文本框顯示的内容
        formatResult: function (row) {
            //轉換成js對象
            var obj = eval('(' + row + ')'); 
            return "文本框顯示的結果:" + obj.key;
        }
    }).result(function (event, row, formatted) {
        //擷取使用者選擇的條目,并轉換成js對象
        var obj = eval('(' + row + ')');  
        alert(obj.key);
    });
});
<body>
    <form id="form1" runat="server">
        請輸入:<input type="text" id="txtAutoComplete" />
    </form>
</body>
           

AutoComplete.ashx背景代碼:

public class AutoComplete : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        //text表示使用者在文本框輸入的内容
        string text = context.Request.QueryString["q"];
        string action = context.Request.QueryString["action"];
        string value = context.Request.QueryString["value"];
        <!--資料格式【不同點2】-->
        <!--各項之間必須用"\n"隔開,不能用","隔開-->        
        string strResult = "{key:\"one\",value:\"第一\"}\n"+
                           "{key:\"two\",value:\"第二\"}\n"+
                           "{key:\"three\",value:\"第三\"}\n"+
                           "{key:\"four\",value:\"第四\"}\n"+
                           "{key:\"five\",value:\"第五\"}\n"+
                           "{key:\"six\",value:\"第六\"}";
        context.Response.Write(strResult);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}
           

ajax動态綁定資料源

前台代碼:

function bindAutoComplete() {
    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: "AutoComplete.aspx/GetHintsInfo",
        data: "{no:'aaa'}",
        dataType: "json",
        success: function (msg) {
            var datas = eval("(" + msg.d + ")");
            $("#txtProjectNO").autocomplete(datas, {
                formatItem: function (row, i, max) {
                    return "<table width='100px'><tr><td align='left'>" + row.ProjectNo + "</td><td align='right'><font style='color: #009933; font-family: 黑體; font-style: italic'>" + row.ProjectName + "</font>&nbsp;&nbsp;</td></tr></table>";
                },
                formatMatch: function (row, i, max) {
                    return row.ProjectNo;
                }
            }).result(function (event, item) {
                $("#txtProjectName").val(item.ProjectName);
                $("#txtDesigner").val(item.Designer);
                $("#txtBudget").val(item.Budget);
            });
        }
    });
}
           

AutoComplete.aspx背景代碼:

[WebMethod]
public static string GetAllHintsSomeField(string no)
{
    List<ProjectInfo> list = new List<ProjectInfo>();
    BLL.CommonBLL commonBLL = new BLL.CommonBLL();
    string where = "IsClosed=0";
    DataTable dt = commonBLL.GetList("View_Project", where);
    for (int i = 0; i < dt.Rows.Count; i++)
    {
        list.Add(new ProjectInfo()
        {
            ProjectNo = dt.Rows[i]["ProjectNo"].ToString(),
            ProjectName = dt.Rows[i]["ProjectName"].ToString(),
            Designer = dt.Rows[i]["Designer"].ToString(),
            Budget = dt.Rows[i]["Budget"].ToString()
        });
    }
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(list.GetType());
    using (MemoryStream ms = new MemoryStream())
    {
        serializer.WriteObject(ms, list);
        return System.Text.Encoding.UTF8.GetString(ms.ToArray());
    }
}
           

extraParams動态傳遞參數

autoComplete可以利用extraParams傳遞參數,如:extraParams:{ para1:‘參數1’, para2:‘參數2’ },

但是如果将動态擷取的值作為參數值卻無法達到目的,如:extraParams:{ userName:$("#userName").val(), age:$("#age").val() },

改進成将方法作為參數值,然後再把實際參數值當做方法的傳回值就可以了,如:

extraParams:{ userName:function(){ return $("#userName").val(); }, age:function(){ return $("#age").val(); } },

$(document).ready(function () {
    //[AutoComplete]1、禁止輸入逗号
    $(".userAC,.domainGroupInfoAC").keydown(function () {
        if (event.keyCode == 188) {
            return false;
        }
    });

    //[AutoComplete]2、對新增的成員控件綁定自動完成功能
    if ($(".userAC").autocomplete) {
        var url = '@Url.Content("~/ACUser/GetUserList/")';
        $(".userAC").autocomplete(url, {
            width: 300,
            minChars: 1,
            cacheLength: 0,
            extraParams: {
                userType: function () { return $("input[name='ApplyUsersType']:checked").val();} },
            multiple: true,
            mustMatch: true,
            formatItem: deptManagerACFormatItem,
            formatResult: deptManagerACFormatResult
        }).result(function (event, item) {
            //showUserMessage();
        });
    }
});
           

頁面加載完畢之後克隆autocomplete綁定的控件會出問題

在工作中經常需要生成動态增加行的表格,此次需要對表格中的文本框綁定autocomplete功能。

表格初始時隻有一行,而且已綁定autocomplete功能,此時當我們通過克隆第一行來增加新行時會出現問題。

折騰了半天,從種種迹象中發現事件其實有綁定,但都綁定在了一開始複制的那一行上面去了,再看看綁定後生成的源代碼,其實JQuery生成的對像都有一個類似jQuery17206059004419403464="3"的屬性;原來在複制行時把這個屬性也複制了,導緻後面的綁定錯位;我們需要用文本框标簽來替換将第一行的autocomplete文本框,這樣新行中的文本框和第一行就沒有任何關系了,然後再對所有控件綁定autocomplete。

//添加節點tr
$("#btnAddAddNode").click(function () {
    var currentMaxStep = $("#addNodeTable tr").filter(".nodeTr").size();
    var nextStep = currentMaxStep + 1;
    var firstTr = $("#addNodeTable tr.nodeTr:eq(0)");
    var newTr = firstTr.clone(true);

    //修改id
    newTr.attr("id", "addNodeTr" + nextStep);
    //設定序号
    newTr.find("td:eq(0)").text(nextStep);
    //設定節點名稱
    var selectText = newTr.find("select:eq(0)").find("option:selected").text();
    newTr.find("input:eq(0)").val(selectText + "審批");
    //設定審批人
    newTr.find("td:eq(3)").html('<input type="text" class="userAC" value="" />');

    newTr.appendTo($("#addNodeTable"));
    //由于添加了class=userAC的控件,是以要重新綁定
    bindAutoComplete();
});
function bindAutoComplete(_this) {
    //[AutoComplete]1、禁止輸入逗号
    $(".userAC").keydown(function () {
        if (event.keyCode == 188) {
            return false;
        }
    });

    //[AutoComplete]2、對新增的成員控件綁定自動完成功能
    if ($(".userAC").autocomplete) {
        var url = '@Url.Content("~/ACUser/GetUserList/")';
        $(".userAC").autocomplete(url, {
            width: 300,
            multiple: false,
            mustMatch: true,
            formatItem: deptManagerACFormatItem,
            formatResult: deptManagerACFormatResult
        }).result(function (event, item) {
            //showUserMessage();
        });
    }
}
           

jquery.autocomplete.min.js檔案免費下載下傳位址:http://download.csdn.net/detail/xiaouncle/9618021

jquery.autocomplete.css檔案免費下載下傳位址:http://download.csdn.net/detail/xiaouncle/9618024