0003. 實現輸入過濾select下拉式選單功能

ASP.Net MVC 學習筆記

<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>實現輸入過濾select下拉式選單功能</title>
    <style type="text/css">
        .Control_Div {
            width: 400px;
            height: 200px;
            top: 100px;
            left: 100px;
            background-color: snow;
            position: absolute;
        }

        .DropDown_HostDiv {
            position: relative;
            float: left;
            width: 120px;
            height: 26px;
        }

        .DropDown_TextBox {
            position: relative;
            width: 100px;
            height: 16px;
        }
        <!-- .DropDown_Container {
            position: relative;
            display: none;
            width: 100px;
            height: 180px;
            border: 1px solid Black;
            overflow: auto;
            overflow-x: hidden;
        }

        .DropDown_Item {
            width: 100%;
            font-family: "Arial", "Georgia", "Verdana", "Helvetica", "sans-serif";
            font-size: 13px;
            background-color: #eafbe5;
            height: 15px;
            color: black;
            border-bottom: 1px solid White;
            padding-top: 4px;
            padding-left: 3px;
        }

            .DropDown_Item:hover {
                background-color: #0BD6DA;
            }
        -->
        .DropDown_Container {
            position: relative;
            top: 2px;
            width: 100%;
            height: 190px;
            overflow: auto;
            overflow-x: hidden;
            border: 1px solid Gray;
        }

            .DropDown_Container table {
                width: 340px;
                height: auto;
                border-collapse: collapse;
            }

                .DropDown_Container table tr {
                    width: auto;
                    padding-top: 1px;
                    height: 15px;
                    font-size: 13px;
                    border-bottom: 1px solid gray;
                    background-color: #F7F4FD;
                    cursor: pointer;
                }

                    .DropDown_Container table tr:hover {
                        background-color: LightBlue;
                    }

                    .DropDown_Container table tr td {
                        font-family: Verdana;
                        border-bottom: 1px solid gray;
                    }
    </style>


    <script language="javascript" type="text/javascript">
        var DpD;
    //當頁面載入時呼叫這個initialtextbox()
    function initialtextbox() {
        window.HXZ;//--建立一個基於該頁面的HXZ的物件
        if (!window.HXZ)//如果物件不為null
        {
            window.HXZ = {}//清空再重新使用
        };

        //該物件具有DropDwon的項目 他擁有下面的功能
        HXZ.DropDown = function (txtObj, _ContainerStyle) {
            var _this = this;
            _this.DataSource;//檔案來源
            _this.DropDown_TextBox = txtObj;//將textbox放進
            _this.SelectedItem;//存放選擇到的項目
            _this.DropDown_Div;//包覆該項目的Div
            _this.DropDown_Items;//DropDown的所有物件
            _this.DropDown_DefaultSelectedItem;//預設選擇到的物件
            _this.ContainerStyle = _ContainerStyle;//使用的style css
            _this.DataSourceSetting = { "KeyFieldStr": "KEY", "ValueFieldStr": "VALUE", "PyFieldStr": "PY" };//Dropdown item格式
            _this.CurrentTimeOutID;//當前ID
            _this.FireWhenConfrimMethod;//當使用者按下DropDownList時的工作 擴展方法
            _this.IsJudgeDirection = false;
            _this.DropDown_DivZindex = 30;
            _this.DropDown_HostDiv = document.body;
            //初始化 指定数据域 以及数据源中 键值字段字符串 和 拼音 字段字符串
            _this.Init = function (_DatataSource, _KeyFieldStr, _ValueFileStr, _PyFieldStr) {
                _this.DataSourceSetting.KeyFieldStr = _KeyFieldStr || "KEY";
                _this.DataSourceSetting.ValueFieldStr = _ValueFileStr || "VALUE";
                _this.DataSourceSetting.PyFieldStr = _PyFieldStr || "PY";
                _this.DataSource = _DatataSource;
                _this.CreateContainer();
                _this.InitItems(_this.DropDown_Div, _this.DataSource);
                _this.InitInputEvent();
            }
            _this.CreateContainer = function () {
                if (_this.DropDown_Div != undefined) {
                    document.body.removeChild(_this.DropDown_Div);
                }
                _this.DropDown_Div = document.createElement("div");
                _this.DropDown_Div.style["zIndex"] = _this.DropDown_DivZindex;
                HXZ.AddEvent(_this.DropDown_Div, "scroll", function () {
                    if (_this.CurrentTimeOutID != undefined || _this.CurrentTimeOutID != null) {
                        window.clearTimeout(_this.CurrentTimeOutID);
                        _this.DropDown_TextBox.focus();
                    }
                });
                HXZ.SetClass(_this.DropDown_Div, _this.ContainerStyle);
                _this.DropDown_HostDiv.appendChild(_this.DropDown_Div);
            }
            ///初始化下拉式選單
            _this.InitItems = function (containerDivObj, data) {
                var table = document.createElement("table");
                var tbody = document.createElement("tbody");
                for (var i = 0; i < data.length; i++) {
                    var tr = document.createElement("tr");
                    var td = document.createElement("td");
                    var itemValue = data[i][_this.DataSourceSetting.ValueFieldStr];
                    td.innerHTML = itemValue;
                    tr.setAttribute("ItemKey", data[i][_this.DataSourceSetting.KeyFieldStr]);
                    tr.setAttribute("ItemValue", itemValue);
                    tr.setAttribute("PY", data[i][_this.DataSourceSetting.PyFieldStr]);
                    HXZ.AddEvent(tr, "click", function (event) {
                        _this.DrowDown_Item_Click(event);
                    });
                    tr.style["display"] = "block";
                    tr.appendChild(td);
                    tbody.appendChild(tr);
                }
                table.appendChild(tbody);
                containerDivObj.appendChild(table);
                _this.DropDown_Items = containerDivObj.getElementsByTagName("tr");
                _this.DropDown_DefaultSelectedItem = _this.DropDown_Items[0];
            }
            //初始化輸入功能 4種事件
            _this.InitInputEvent = function () {
                HXZ.AddEvent(_this.DropDown_TextBox, "click", function (event) {
                    _this.ShowItems(event);
                });
                //當使用者輸入在input時 要對Input做關鍵字索引
                HXZ.AddEvent(_this.DropDown_TextBox, "keyup", function (event) {
                    _this.DropDown_KeyUp(event);
                });
                HXZ.AddEvent(_this.DropDown_TextBox, "keydown", function (event) {
                    _this.DropDown_KeyDown(event);
                });
                HXZ.AddEvent(_this.DropDown_TextBox, "blur", function (event) {
                    _this.DropDown_TextBox_Blur(event);
                });
            }
            _this.ShowItems = function (event) {
                _this.DropDown_Div.style["display"] = "block";
            }
            _this.DropDown_KeyDown = function (event) {
                var e = window.event || event;
                if (_this.DropDown_Div.style["display"] == "none") {
                    _this.DropDown_Div.style["display"] = "block";
                }
                var theItem = _this.SelectedItem == undefined || _this.SelectedItem == null ? HXZ.getFirstUnHideChildByTagName(_this.DropDown_Div, "tr") : _this.SelectedItem;
                switch (e.keyCode) {
                    case 40://鍵盤的向下鍵 ↓
                        //如果走到底了 就選擇目前的項目(通常是最後一項)
                        if (_this.SelectedItem == undefined || _this.SelectedItem == null) {
                            _this.DrowDown_ItemSelected(theItem);
                        }
                        else//否則就往下一個項目做移動
                        {
                            _this.DrowDown_ItemSelected(HXZ.GetNextUnHideSibling(theItem));
                        }
                        break;
                    case 38://鍵盤的向上鍵 ↑
                        _this.DrowDown_ItemSelected(HXZ.GetPreUnHideSibling(theItem));
                        break;
                    case 13://按下Enter鍵時
                        _this.DropDown_Confirm(theItem);
                        break;
                }
            }
            //當使用者輸入在input時 要對Input做關鍵字索引
            _this.DropDown_KeyUp = function (event) {
                var items = _this.DropDown_Div.getElementsByTagName("tr");
                var e = window.event || event;
                if (e.keyCode == 40 || e.keyCode == 38) {
                    return;
                }
                //對當前的輸入的字將空白移除
                var TextBoxValue = _this.DropDown_TextBox.value.toString().Trim();
                //如果是空白就取得所有資料
                if (TextBoxValue == "") {
                    for (var i = 0; i < items.length; i++) {
                        items[i].style["display"] = "block";
                    }
                    return;
                }
                //比對規則
                var regStr = '^' + TextBoxValue + '\w*';

                var reg = new RegExp(regStr, "g");

                for (var i = 0, j = items.length; i < j; i++) {
                    var theItem = items[i];
                    //reg.test() Tests for a match in a string. Returns true or false
                    var f = reg.test(theItem.getAttribute("PY").toString()) || reg.test(theItem.innerHTML.toString().Trim());
                    //取得字串的內容是否有包含上述準則
                    var ff = reg.test(theItem.getAttribute("ItemValue").toString().Trim());
                    var IsMatch = f || ff;

                    if (IsMatch) {
                        theItem.style["display"] = "block";
                    }
                    else {
                        theItem.style["display"] = "none";
                    }
                }
                if (e.keyCode != 13) {
                    _this.SelectedItem = null;
                }
            }
            _this.DrowDown_ItemSelected = function (itemObj) {
                if (itemObj == undefined || itemObj == null) {
                    if (_this.DropDown_DefaultSelectedItem != null) {
                        _this.DrowDown_ItemSelected(_this.DropDown_DefaultSelectedItem);
                    }
                    return;
                }
                if (_this.SelectedItem != undefined && _this.SelectedItem != null) {
                    _this.SelectedItem.style["backgroundColor"] = "";
                }
                _this.SelectedItem = itemObj;
                _this.SelectedItem.style["backgroundColor"] = "lightBlue";
                _this.DrowDown_Scroll(_this.SelectedItem);
            }
            _this.DrowDown_Scroll = function (itemObj) {
                var item_height = itemObj.offsetHeight + 10;
                _this.DropDown_Div.scrollTop = itemObj.offsetTop + item_height - _this.DropDown_Div.offsetHeight >= 0 ? itemObj.offsetTop + item_height - _this.DropDown_Div.offsetHeight : 0;
            }
            //當使用者按下Enter鍵時
            _this.DropDown_Confirm = function (itemObj) {
                if (itemObj == undefined || itemObj == null) {
                    _this.SelectedItem = null;
                    return;
                }
                _this.DropDown_TextBox.focus();
                var itemValue = itemObj.getAttribute("ItemValue");
                var itemKey = itemObj.getAttribute("ItemKey");
                _this.DropDown_TextBox.value = itemValue;
                _this.DropDown_TextBox.setAttribute("ItemKey", itemKey);
                _this.DropDown_TextBox.setAttribute("SelectedValue", itemValue);
                if (_this.FireWhenConfrimMethod != undefined) {
                    _this.FireWhenConfrimMethod(itemValue, itemKey);
                }
                itemObj.style["backgroundColor"] = "";
                _this.SelectedItem = itemObj;
                _this.DropDown_Div.style["display"] = "none";
            }
            //Downloads By http://www.veryhuo.com
            _this.DrowDown_Item_Click = function (event) {
                var t = HXZ.getSrcElement(event);
                if (t == null) {
                    return;
                }
                while (t.tagName != "TR") {
                    t = t.parentNode;
                }
                _this.DrowDown_ItemSelected(t);
                _this.DropDown_Confirm(t);
            }
            _this.DropDown_TextBox_Blur = function (event) {
                _this.CurrentTimeOutID = window.setTimeout(function () { _this.DropDown_Div.style["display"] = "none" }, 160);
                if (_this.DropDown_TextBox.value.Trim() == "") {
                    _this.SelectedItem = HXZ.getFirstUnHideChildByTagName(_this.DropDown_Div, "div");
                }
                //如果用户更改了输入框的值的时候,我们自动将其修复
                var SelectedValue = _this.DropDown_TextBox.getAttribute("SelectedValue");
                _this.DropDown_TextBox.value = SelectedValue == null ? "" : SelectedValue;
            }
        }
        HXZ.insertAfter = function (newEl, targetEl) {
            var parentEl = targetEl.parentNode;
            if (parentEl.lastChild == targetEl) {
                parentEl.appendChild(newEl);
            } else {
                parentEl.insertBefore(newEl, targetEl.nextSibling);
            }
        }
        HXZ.getSrcElement = function (e) {
            var ee = e || window.event;
            if (!document.all) {
                return ee.target;
            }
            return ee.srcElement;
        }
        HXZ.AddEvent = function (obj, eve_str, handle) {
            if (window.attachEvent) {
                obj.attachEvent("on" + eve_str, handle);
            }
            else if (window.addEventListener) {
                obj.addEventListener(eve_str, handle, true);
            }
        }
        HXZ.RemoveEvent = function (obj, eve_str, handle) {
            if (window.detachEvent) {
                obj.detachEvent("on" + eve_str, handle);
            }
            else if (window.removeEventListener) {
                obj.removeEventListener(eve_str, handle, true);
            }
        }
        HXZ.AddEvents = function (obj, eve_array, handle_arr) {
            for (var i = 0; i < eve_array.length; i++) {
                HXZ.AddEvent(obj, eve_array[i], handle_arr[i]);
            }
        }
        HXZ.SetClass = function (obj, cssStyle) {
            obj.setAttribute("class", cssStyle);
            obj.setAttribute("className", cssStyle);
        }
        String.prototype.ToJson = function () {
            var json;
            try {
                json = eval('(' + this + ')');
            }
            catch (e) {
            }
            return json;
        };
        String.prototype.Trim = function () {
            return this.replace(/(^\s*)|(\s*$)/g, "");
        }
        HXZ.GetNextSibling = function (ele) {
            if (ele == null) {
                return ele;
            }
            var _ele = ele.nextSibling;
            if (_ele == null) {
                return null;
            }
            while (_ele.nodeType != 1) {
                _ele = _ele.nextSibling;
            }
            return _ele;
        }
        HXZ.GetPreSibling = function (ele) {
            if (ele == null) {
                return ele;
            }
            var _ele = ele.previousSibling;
            if (_ele == null) {
                return null;
            }
            while (_ele.nodeType != 1) {
                _ele = _ele.previousSibling;
            }
            return _ele;
        }
        HXZ.GetNextUnHideSibling = function (ele) {
            var _ele = HXZ.GetNextSibling(ele);
            if (_ele == null) {
                return null;
            }
            while (_ele.style["display"] == "none") {
                _ele = HXZ.GetNextUnHideSibling(_ele);
                if (_ele == null) {
                    return null;
                }
            }
            return _ele;
        }
        HXZ.GetPreUnHideSibling = function (ele) {
            var _ele = HXZ.GetPreSibling(ele);
            if (_ele == null) {
                return null;
            }
            while (_ele.style["display"] == "none") {
                _ele = HXZ.GetPreUnHideSibling(_ele);
                if (_ele == null) {
                    return null;
                }
            }
            return _ele;
        }
        HXZ.getElementPosition = function (obj) {
            var obj1 = obj;
            var position = { "left": obj1.offsetLeft, "top": obj1.offsetTop };
            while (obj1.offsetParent) {
                obj1 = obj1.offsetParent;
                position.left += obj1.offsetLeft;
                position.top += obj1.offsetTop;
            }
            while (obj.parentNode != document.body) {
                obj = obj.parentNode;
                position.left -= obj.scrollLeft;
                position.top -= obj.scrollTop;
            }
            return position;
        }
        HXZ.getFirstUnHideChildByTagName = function (obj, tagNameStr) {
            var Childs = obj.getElementsByTagName(tagNameStr);
            for (var i = 0, j = Childs.length; i < j; i++) {
                if (Childs[i].style["display"] == "block") {
                    return Childs[i];
                }
            }
            return null;
        }




        //==========  保管場所資料匯入到 DropDownList ajax呼叫
        //var Get = [{ "KEY": "0", "VALUE": "保管場所名稱", "PY": "0" }];//格式定義
        //var DropDownListParam = {
        //    'Level': '',//------------------------當前選單要搜尋的欄位
        //};
        //$.ajax({
        //    type: 'POST',
        //    url: MyRoot() + "/api/ResourceSummaryApi/GetDropDownListPlaceName",
        //    data: DropDownListParam,  //------------------------參數丟入
        //    success: function (data) {

        //        //將原本的移除
        //        Get.pop();
        //        //將取得的資料建立成保管場所下拉式選單
        //        for (var i = 0; i < data.length; i++) {
        //            Get.push({ "KEY": data[i], "VALUE": data[i], "PY": i });
        //        }
        //        //ID = DropDown_TextBox 輸入的Input
        //        var _DropDown_TextBox = document.getElementById("DropDown_TextBox");
        //        //加入style css 名為DropDown_Container
        //        DpD = new HXZ.DropDown(_DropDown_TextBox, "DropDown_Container");
        //        //將下拉式選單放進div DropDown_HostDiv中
        //        DpD.DropDown_HostDiv = document.getElementById("DropDown_HostDiv");
        //        //建立一個需要itemValue, itemKey 的DpD_FireWhenConfrimMethod 當使用者按下DropDownList時的工作
        //        DpD.FireWhenConfrimMethod = DpD_FireWhenConfrimMethod;
        //        //Dropdown List的初始化
        //        DpD.Init(Get, "KEY", "VALUE", "PY");
        //    }
        //});
         
        var data = [
{ "KEY": "20151118", "VALUE": "劉備", "PY": "aaa" },
{ "KEY": "20151118", "VALUE": "關羽", "PY": "bbb" },
{ "KEY": "20151118", "VALUE": "張飛", "PY": "ccc" }
        ];

       
        window.onload = function () {
            var _DropDown_TextBox = document.getElementById("DropDown_TextBox");
            DpD = new HXZ.DropDown(_DropDown_TextBox, "DropDown_Container");
            DpD.DropDown_HostDiv = document.getElementById("DropDown_HostDiv");
            DpD.FireWhenConfrimMethod = DpD_FireWhenConfrimMethod;
            DpD.Init(data, "KEY", "VALUE", "PY");
        }


    }

    //當使用者按下DropDownList時的工作
    function DpD_FireWhenConfrimMethod(itemValue, itemKey) {
    }


    </script>
</head>
<body onload="initialtextbox()">
    <div>
        <span style='float: left; font-weight: bold'>姓名:</span>
        <div id="DropDown_HostDiv">
            <input type="text" id="DropDown_TextBox" />
        </div>
    </div>
</body>