Jquery实现自动提示下拉框

时间:2021-04-17 21:33:00

1、引入脚本库:
    <script type="text/javascript"
src="/Jscripts/jquery-1.3.2.js"></script>

<script src="/Jscripts/jquery.autocomplete.js"
type="text/javascript"></script>

2、在Demo.aspx页面中加入如下脚本:
       
$(document).ready(function() {
           
$.ajax({
               
type: "POST",
               
contentType: "application/json",
               
url: "Demo.aspx/GetDataBind",
               
data: "{}",
               
dataType: "json",
               
success: function(msg) {
                   
var datas = eval_r('(' + msg.d + ')');
                   
$("#txtName").autocomplete(datas,
{
                       
max: 12,
                       
minChars: 0,
                       
width: 140,
                       
scrollHeight: 300,
                       
matchContains: true,
                       
autoFill: false, //自动填充
                       
formatItem: function(row, i, max, value) {
                           
return row.Key;
                       
},
                       
formatMatch: function(row, i, max, value) {
                           
return row.Key;
                       
},
                       
formatResult: function(row) {
                           
return row.Key;
                       
}
                   
}).result(function(event, row, formatted) {
                       
$("#hidID").val(row.Value);
                   
});
               
}
           
});
       
});
3、页面中需要提供txtName、hidID控件:
    <asp:TextBox ID="txtName"
runat="server"></asp:TextBox>

<asp:HiddenField ID="hidID" runat="server"
/>
   
4、Demo.aspx.cs后台代码:

[WebMethod]
       
public static string GetDataBind()
       
{
           
Dictionary data = new Dictionary();

IList userinfos = GetByName();
           
if (userinfos != null)
           
{
               
foreach (Employee e in userinfos)
               
{
                   
data.Add(e.cName + "-" + e.eName, e.Empno);
               
}
           
}
           
DataContractJsonSerializer serializer = new
DataContractJsonSerializer(data.GetType());
           
using (MemoryStream ms = new MemoryStream())
           
{
               
serializer.WriteObject(ms, data);
               
return System.Text.Encoding.UTF8.GetString(ms.ToArray());
           
}
       
}