Textbox search autocompalety

本文介绍了一个基于jQuery的文本框搜索插件,支持键盘上下键导航,并提供了详细的使用示例和代码实现。插件能够根据输入关键词从服务器获取数据并展示下拉列表供用户选择。

源码:

//@name Textbox search autocompalety
//@version 0.1
//@author Ni
//@description 文本框搜索插件,支持键盘上下键
(function ($) {
$.setOptions = function (k, p) {
p = $.extend({
IsShowSearchList: false, //是否显示搜索列表
SearchValue: "", //作为搜索条件的值
TextSearchSelectedIndex: "", //当前下拉列表所选的索引
TextSearchList: new Array(), //下拉列表的数据源
TimeoutSearch: null, //延迟搜索
Left: 0, //div显示位置 X
Top: 0, //div显示位置 Y
RecordCount: 0, //符合搜索条件的记录行数

TimeoutNum: 500, //【可配置】延迟搜索 单位:毫秒
Width: "500px", //【可配置】div宽度
Url: "", //【可配置】取值方法地址
MinSearchLength: 1, //【可配置】最小搜索关键词长度
MaxRowCount: 10, //【可配置】搜索框最多显示行数 显示全部为-1
onSelect: false //【可配置】行选中事件
}, p);

var t = {
hideTxtSearchList: function () {
clearTimeout(p.TimeoutSearch);
if ($(".TxtSearchFoucs").attr('v') != undefined || $(".TxtSearchFoucs").attr('v')!=null)
p.TextSearchSelectedIndex = parseInt($(".TxtSearchFoucs").attr('v'));
if (p.TextSearchSelectedIndex != "") {
t.selectTxtSearch(p.TextSearchSelectedIndex);
}
p.IsShowSearchList = false;
p.TextSearchSelectedIndex = "";
$("#divTxtSearch").hide();
$("#divTxtSearch").empty();
$("#iframeOpenTxt").hide();
},
getTxtSearchList: function () {
var e = document.getElementById($(k).attr('id'));
if (e.value.length < p.MinSearchLength) return;
if (event.keyCode == 38 || event.keyCode == 40) {
if (p.IsShowSearchList == false) return;
//上下移动事件
if (event.keyCode == 38)
t.selectTxtSearchUp();
if (event.keyCode == 40)
t.selectTxtSearchDown();

p.SearchValue = e.value;
return;
}
p.Left = t.aspnm_pageX(e) + 1;
p.Top = t.aspnm_pageY(e) + 20;
p.SearchValue = e.value;
clearTimeout(p.TimeoutSearch);
p.TimeoutSearch = setTimeout(function () {
$.ajax({
url: p.Url + encodeURI(p.SearchValue) + "&pagesize=" + p.MaxRowCount,
dataType: "json",
type: "POST",
success: function (da) {
p.TextSearchList = new Array();
p.RecordCount = da.total;
for (var i = 0; i < da.rows.length; i++) {
p.TextSearchList[i] = da.rows[i].row;
}
t.crateTxtSearchList();
}
});
}, p.TimeoutNum);
},

//创建下拉列表
crateTxtSearchList: function () {
p.IsShowSearchList = true;
p.TextSearchSelectedIndex = "";
$("#divTxtSearch").empty();
var html;
if (p.TextSearchList.length > 0) {
html = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"width: 100%;\">";
var rowCount = (p.MaxRowCount == -1 || p.MaxRowCount > p.TextSearchList.length) ? p.TextSearchList.length : p.MaxRowCount;
for (var i = 0; i < rowCount; i++) {
var listItem = p.TextSearchList[i].split(',');
html += "<tr class=\"TxtSearchNotFoucs\" id=\"TRTxtSearch" + (i + 1) + "\" onmouseout=\"this.className=\'TxtSearchNotFoucs\'\" onmouseover=\"this.className=\'TxtSearchFoucs\';\" v='" + (i + 1) + "'> ";
for (var j = 0; j < listItem.length; j++) {
html += "<td style=\"padding-left: 3px\">" + listItem[j] + "</td>";
}
html += "</tr>";
}
html += "</table>";
if (p.RecordCount > rowCount) {
html += "<div style='font-size:12px;text-align:right;color:red;"
+ "line-height:18px;background-color:White'>未列出所有搜索结果!</div>";
}
} else {
html = "<div style='font-size:12px;text-align:right;"
+ "color:red;line-height:18px;background-color:White'>搜索完毕,没有结果可以显示!</div>";
}
$("#divTxtSearch").show();
$("#divTxtSearch").html(html);
$("#iframeOpenTxt").show();
$("#divTxtSearch").css("left", p.Left);
$("#divTxtSearch").css("top", p.Top);
$("#divTxtSearch").css("width", p.Width);

t.setOpenTxtIframe();
},
//设置Iframe
setOpenTxtIframe: function () {
$("#iframeOpenTxt").show();
$("#iframeOpenTxt").css("left", p.Left);
$("#iframeOpenTxt").css("top", p.Top);
$("#iframeOpenTxt").css("width", document.getElementById('divTxtSearch').offsetWidth + "px");
$("#iframeOpenTxt").css("height", document.getElementById('divTxtSearch').offsetHeight + "px");
},
//X
aspnm_pageX: function (element) {
var x = 0;
do
x += element.offsetLeft;
while ((element = element.offsetParent));
return x;
},
//Y
aspnm_pageY: function (element) {
var y = 0;
do
y += element.offsetTop;
while ((element = element.offsetParent));
return y;
},
//鼠标的选择行事件
selectTxtSearchMouse: function (rowIndex) {
if ($(".TxtSearchFoucs").attr('v') != undefined || $(".TxtSearchFoucs").attr('v') != null)
p.TextSearchSelectedIndex = parseInt($(".TxtSearchFoucs").attr('v'));
if (p.TextSearchSelectedIndex != '')
$("#TRTxtSearch" + p.TextSearchSelectedIndex).attr("class", "TxtSearchNotFoucs");
$("#TRTxtSearch" + rowIndex).attr("class", "TxtSearchFoucs");
p.TextSearchSelectedIndex = rowIndex;
},
//点击'上'触发的js事件
selectTxtSearchUp: function () {
if ($(".TxtSearchFoucs").attr('v') != undefined || $(".TxtSearchFoucs").attr('v') != null)
p.TextSearchSelectedIndex = parseInt($(".TxtSearchFoucs").attr('v'));
if (p.TextSearchSelectedIndex == '' || parseInt(p.TextSearchSelectedIndex) == 1) {
//最后一个
t.selectTxtSearch(p.TextSearchList.length);
}
else {
//上移
t.selectTxtSearch(parseInt(p.TextSearchSelectedIndex) - 1);
}
},
//点击'下'触发的js事件
selectTxtSearchDown: function () {
if ($(".TxtSearchFoucs").attr('v') != undefined || $(".TxtSearchFoucs").attr('v') != null)
p.TextSearchSelectedIndex = parseInt($(".TxtSearchFoucs").attr('v'));
if (p.TextSearchSelectedIndex == '' || parseInt(p.TextSearchSelectedIndex) == p.TextSearchList.length) {
//第一个
t.selectTxtSearch('1');
}
else {
//下移
t.selectTxtSearch(parseInt(p.TextSearchSelectedIndex) + 1);
}
},
//选择行
selectTxtSearch: function (rowIndex) {
if (p.TextSearchSelectedIndex != '')
$("#TRTxtSearch" + p.TextSearchSelectedIndex).attr("class", "TxtSearchNotFoucs");
$("#TRTxtSearch" + rowIndex).attr("class", "TxtSearchFoucs");
p.TextSearchSelectedIndex = rowIndex;

//将值写到页面指定元素 方法自己实现
var rowData = p.TextSearchList[rowIndex - 1].split(',');
if (p.onSelect) p.onSelect(rowData);
}
};
$(k).keyup(function () {
t.getTxtSearchList();
});
$(k).blur(function () {
t.hideTxtSearchList();
});
};
//程序入口
$.fn.TxtSearch = function (p) {
this.each(function () {
$.setOptions(this, p);
});
};
})(jQuery);

document.write('<div id="divTxtSearch" style="border: black 1px solid; width: 269px; display: none;position: absolute; z-index: 9999;"></div>'
+ '<iframe id="iframeOpenTxt" frameborder="0" style="visibility: hidden;position: absolute; z-index: 9000;"></iframe>');

  效果图:

调用方式:

//自动搜索
    $("#txt1").TxtSearch({
        Url: "/httpHandler/SystemManagement/HandlerDemo.ashx?type=getpname&key=",
        Width: "460",
        onSelect: function (rowData) {
            $('#hid1').val(rowData[0]);
            $('#txt1').val(rowData[1]);
        }
    });

  

private MenuFun _instance = DataFactory.CreateInstance<MenuFun>("MenuFun", AssemblyKey.BusRoles); 
    private CommonFun commonFun = DataFactory.CreateInstance<CommonFun>("CommonFun", AssemblyKey.BusComm);
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        context.Response.Write(Handler(context));
    }

public string Handler(HttpContext context)
    {
        string src = context.Request["type"];
        switch (src)
        {
            case "getpname":
                return GetPName(context);
            default:
                return string.Empty;
        }
    }

string GetPName(HttpContext context)
    {
        string pageSize = context.Request["pagesize"];
        if (string.IsNullOrEmpty(pageSize)) pageSize = "100";
        if (pageSize == "-1") pageSize = "10000";
        string where = "";
        string key = context.Request["key"];
        if (!string.IsNullOrEmpty(key))
        {
            if (Utils.IsNumber(key))
                where = string.Format(" and FUNMODEL_CD = '{0}'", key);
            else if(Utils.IsEnglish(key))
            {
                where = string.Format(" and dbo.f_GetPy(FUNMODEL_NM) like '%{0}%'", key);
            }
            else
            {
                where = string.Format(" and FUNMODEL_NM like '%{0}%'", key);
            }
        }
        DataSet ds = commonFun.GetLimitPageData("v_CYP_MenuName", "FUNMODEL_CD, FUNMODEL_NM,FUNMODEL_LEV,MAXID", where, "FUNMODEL_CD", 1, int.Parse(pageSize));

        if (ds != null && ds.Tables.Count == 2 && ds.Tables[1].Rows.Count > 0)
        {
            string json = "{\"total\":" + ds.Tables[0].Rows[0][0] + ",\"rows\":[";
            foreach (DataRow dataRow in ds.Tables[1].Rows)
            {
                json += "{\"row\":\"";
                json = ds.Tables[1].Columns.Cast<DataColumn>().Aggregate(json, (current, dataColumn) => current + (dataRow[dataColumn] + ","));
                json = json.Substring(0, json.Length - 1) + "\"},";
            }
            json = json.TrimEnd(',') + "]}";
            return json;
        }
        return "{\"total\":0,\"rows\":[]}";
    }

  

转载于:https://www.cnblogs.com/nimin961145/archive/2013/02/19/2917388.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值