日期:2014-05-17  浏览次数:20424 次

textbox中输入字符在下拉框中联想
页面上有两个控件textbox和dropdownlist控件,页面加载的时候在下拉框中绑定了数据,在textbox中输入内容后,在下拉框中寻找匹配的内容,类似于联想的功能,但页面不能有刷新,小弟JS很菜,写不出来,请大家帮帮忙。

------解决方案--------------------
HTML code
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtFilterCity" runat="server" onkeyup="filterCity(this);"></asp:TextBox><br />
        <asp:DropDownList ID="ddlCityList" runat="server">
        </asp:DropDownList>
    </div>

    <script type="text/javascript">
        var store = [];
        window.onload = function() {
            var citys = document.getElementById('ddlCityList');
            for (var i = 0; i < citys.options.length; i++) {
                var city = {
                    id: citys.options[i].value,
                    name: citys.options[i].text
                };
                store.push(city);
            }
        }
        function filterCity(o) {
            var citys = document.getElementById('ddlCityList');
            citys.options.length = 0;
            if (o.value != '') {
                for (var j = 0; j < store.length; j++) {
                    if (store[j].name.indexOf(o.value) >= 0) {
                        var option = new Option();
                        option.value = store[j].id;
                        option.text = store[j].name;
                        citys.options.add(option);
                    }
                }
            } else {
                for (var j = 0; j < store.length; j++) {
                    var option = new Option();
                    option.value = store[j].id;
                    option.text = store[j].name;
                    citys.options.add(option);
                }
            }
        }
    </script>

    </form>