未古其人

目录

用于模糊搜索的下拉列表

网上找的代码都太繁琐,还有各种插件、CSS,折腾的要死,最后手写发现也不难嘛~ HTML代码

<li class="like_search_box">
    <input class="detail_inputs_needs_corp" onkeyup="changeNeedsCorpInput(this, 'add')"  id="add_needs_corp_input" />
    <input id="add_needs_corp_hidden" type="hidden" name="add_needs_corp" />
    <select class="like_search_select" id="add_select_needs_corp" size="10" style="display:none;"></select>
</li>

下面是用于控制的JS代码

// 这部分用AJAX或者其他方式获得
var testData = [
    {
        name: "牙膏厂",
        corpId: '1234'
    }, {
        name: "熊厂",
        corpId: '1235'
    }, {
        name: "企鹅公司",
        corpId: '1236'
    }, {
        name: "粗粮公司",
        corpId: '1237'
    }, {
        name: "菊花社",
        corpId: '1238'
    }, {
        name: "美帝良心想",
        corpId: '1239'
    }, {
        name: "养猪场",
        corpId: '1240'
    }
];
function changeNeedsCorpInput(element, type) {

    // 这部分是AJAX替换
    var list = [];

    for (var i = 0, len = proto.length; i < len; i++) {
        var item = proto[i];
        if (item.name.indexOf(str) >= 0) {
            list.push(item);
        }
    }
    // list的具体实现交给后台sql决定

    var str = element.value;
    var select = $("#" + type + "_select_needs_corp");

    if (!str) {// 空输入时隐藏select
        select.empty();
        select.css({
            "display": "none"
        });
        return;
    };

    var input = $("#" + type + "_needs_corp_input");
    var hiddenInput = $("#" + type + "_needs_corp_hidden");

    setTimeout(function () { // TODO AJAX 替换位

        select.empty();

        for (var i = 0, len = list.length; i < len; i++) {
            (function(item) {
                var option = $("<option value='" + item.corpId + "'>" + item.name + "</option>");
                option.css({
                    "height": 22 * list + "px",
                    "padding":"2px"
                });
                option.on('click', function () {
                    input.val(item.name);
                    hiddenInput.val(item.corpId);
                    select.css({
                        "display": "none"
                    });
                });
                select.append(option);
            })(list[i]);

        }

        if (list.length > 0) {
            select.css({
                "display": "block",
                "height": 24 * list.length + "px"
            });
        }

    }, 100);// 从后台加载数据
}