实时搜索(在键入时动态过滤结果) - Bootstrap,jQuery

时间:2016-09-14 11:57:36

标签: javascript jquery html css twitter-bootstrap

我希望能够在我的应用程序中进行实时搜索(在键入时动态过滤搜索结果)。我现在正在努力使用jQuery。

代码:

<div id="appFormSubType">
    <label class="g-label control-label">Select application form sub-type:</label>
    <select class="form-control">
        <option value="notSelected">Not Selected</option>
        <option value="first">First</option>
        <option value="second">Second</option>
        <option value="third">Third</option>
        <option value="fourth">Fourth</option>
    </select>
        <label class="some-label control-label">New or existing?</label>
        <input class="form-control" placeholder="Search" type="search" id="accountSearch">
        <select multiple class="form-control" id="existingAccounts">
            <option value="newAccount">New Account</option>
        </select>
</div>

用于获取existingAccounts数据的函数:

$.getJSON("/accounts.json", function(data){
    $.each(data.items, function(i, item){
        $('#existingAccounts').append($('<option>').text(item.name).attr('value', item.id));
    })
});

所以我在考虑在keyup上生成搜索查询。

$('#accountSearch').on('keyup', function(){
        var searchTerm = $(this).val().toLowerCase();
        console.log("Search Form - Keyup: " + searchTerm);
});

但我不知道如何动态过滤结果。

1 个答案:

答案 0 :(得分:1)

Html部分

更改自动填充短划线属性以指向源值

<div class="input-group input-group-sm" style="width: 500px;">
    <input type="search" name="searchTerm" class="form-control pull-right ui-autocomplete-input" placeholder="search" data-ac-autocomplete="accounts.json" autocomplete="off">
    <div id="containerAc">
        <ul id="ui-id-1" tabindex="0" class="ui-menu ui-widget ui-widget-content ui-autocomplete ui-front" style="display: none;"></ul>
    </div>  
</div>

脚本部分

$(document).ready(function () {
    // just in case to have more than one place you want to use it.
    $("input[data-ac-autocomplete]").each(function () {
        var control = new searchNs.Autocomplete();
        var input = $(this);
        control.createAutocomplete(input);
    });
});

作为分离文件中的库

var searchNs = searchNs || {};

searchNs.Autocomplete = function () {
    this.targetElement = 'data-target';
    this.container = '#containerAc';
    this.sourceAttibute = 'data-ac-autocomplete';
}
searchNs.Autocomplete.prototype = function () {
    var submitAutocompleteForm = function(event, ui) {
        var input = $(this);
        input.val(ui.item.label);

        var form = input.parents('form:first');
    },
    createAutocomplete = function (input) {
        var self = this;

        var options = {
            minLength:2,
            // The place to find the values, like your accounts.json
            source: input.attr(self.sourceAttibute),
            select: submitAutocompleteForm,
            appendTo: self.container
        };

        input.autocomplete(options);
    };
    return {createAutocomplete: createAutocomplete }
}();