您的位置:首页 > Web前端 > JQuery

jquery autocomplete 自动补全

2015-08-05 22:00 811 查看

写在前面

  autocomplete是jqueryUI里的一个插件

  效果和说明可以访问这里,作用类似于搜索时的自动提示:

相信用过jQuery autocomplete 自动补全功能同学有不少,但是往往我们所对应的需求不同,有的仅仅是为了省事,敲两个字就有一堆可供选择的信息可供选择,但并不是所有需求都是这样的,我们还有这样的需求,敲两个字,将这个文字对应的实体绑定出来。

主要的参数

jQuery UI Autocomplete常用的参数有:

Source:用于指定数据来源,类型为String、Array、Function
String:用于ajax请求的服务器端地址,返回Array/JSON格式

Array:即字符串数组 或 JSON数组

Function(request, response):通过request.term获得输入的值,response([Array])来呈现数据;(JSONP是这种方式)

minLength:当输入框内字符串长度达到minLength时,激活Autocomplete

autoFocus:当Autocomplete选择菜单弹出时,自动选中第一个

delay:即延迟多少毫秒激活Autocomplete

其他不常用的就不罗列了。

需要引用的文件

<link href="/Content/jquery.autocomplete.css" rel="stylesheet" type="text/css" />

  <script type="text/javascript" src="/Scripts/jquery.autocomplete.js"></script>
<script type="text/javascript">
function initAutoComplete(json) {
$("#inputxt").autocomplete(json, {
minChars: 1,
width: 260,
dataType: "json",
matchContains: true,
formatItem: function (row, i, max) {
return row.id + " <" + row.title + ">";
},
formatMatch: function (row, i, max) {
return row.title;
},
formatResult: function (row) {
return row.title;
}

}).result(function (event, row, formatted) {
$("#newid").val(row.id);
}); ;
}
$(document).ready(function () {
$("#inputxt").focus(function () {
$.post("/ashx/AccessDate.ashx", {}, function (data) {
initAutoComplete(data);
}, "json");
});
});
</script>


前台:

<form action="" method="post">
<input type="text" id="inputxt" />
<input type="hidden" id="newid" />
<input type="submit" value="提交"/>
</form>


这些代码的意思就是在文本框输入搜索文字后,智能提示出对应的列表以及列表所对应的ID,选择某一条后,将ID赋值给隐藏域,这样提交表单的时候就可以将文本框内容与ID

一起提交。

后台:

       JavaScriptSerializer jss = new JavaScriptSerializer();
Dictionary<string, string> drow = new Dictionary<string, string>();
List<Dictionary<string, object>> gas = new List<Dictionary<string, object>>();
string start = System.Web.HttpUtility.UrlDecode(context.Request["start"], Encoding.UTF8);

string end = System.Web.HttpUtility.UrlDecode(context.Request["end"], Encoding.UTF8);
SqlConnection con = new SqlConnection(SqlHelper.sqlCon);
SqlDataAdapter da = new SqlDataAdapter("SELECT   ID, Title, start, [end], UserID, fullname, confname, confshortname, allDay, topic, [description]  FROM  Userdate ", con);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
Dictionary<string, object> drow2 = new Dictionary<string, object>();
drow2.Add("id", ds.Tables[0].Rows[i]["ID"].ToString());
drow2.Add("title", ds.Tables[0].Rows[i]["Title"].ToString());
gas.Add(drow2);
}
context.Response.Write(jss.Serialize(gas));




  


效果就是这样了,下面把所需文件奉上

点击下载

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: