过滤引导按钮列表

时间:2016-07-27 18:35:34

标签: javascript jquery twitter-bootstrap

我有一个引导按钮列表,还有一个搜索框,我想实现一个过滤功能(最好用javascript)来过滤按钮数量:

引导代码在这里:

https://jsfiddle.net/7zyrdnab/

    <div class="row">
    <div class="col-lg-2">
        <div class="panel">
        <input type="text" id="search" placeholder="Type to search">
        <br>
           <button type="button" class="btn btn-secondary">AA1009</button>
           <button type="button" class="btn btn-secondary">AA1010</button>
           <button type="button" class="btn btn-secondary">BA1098</button>
           <button type="button" class="btn btn-secondary">BB1890</button>
           <button type="button" class="btn btn-secondary">C89761</button>
           <button type="button" class="btn btn-secondary">CD1667</button>
           <button type="button" class="btn btn-secondary">GG7830</button>
           <button type="button" class="btn btn-secondary">GF65372</button>
           <button type="button" class="btn btn-secondary">BH6537</button>
           <button type="button" class="btn btn-secondary">HGB562</button>
           <button type="button" class="btn btn-secondary">LK9063</button>
           <button type="button" class="btn btn-secondary">CP9871</button>
           <button type="button" class="btn btn-secondary">IRON87</button>
           <button type="button" class="btn btn-secondary">ACT567</button>
           <button type="button" class="btn btn-secondary">MPO760</button>
           <button type="button" class="btn btn-secondary">GH5436</button>
           <button type="button" class="btn btn-secondary">NBH894</button>
           <button type="button" class="btn btn-secondary">GHFDF6</button>
           <button type="button" class="btn btn-secondary">US4536</button>
           <button type="button" class="btn btn-secondary">MO9854</button>
                     </div>
    </div>
</div>

过滤器应该像这样工作: 如果键入AA,则只显示带有文本&#34; aa&#34;的按钮。应该是可见的。

我在网上搜索时得到的唯一建议是使用list.js,但我想知道是否可以有一个更简单的javascript搜索实现。

1 个答案:

答案 0 :(得分:3)

https://jsfiddle.net/Shuaso/qhku76bu/

jquery:

var $button = $('.btn');

$('#search').keyup(function() {
    var re = new RegExp($(this).val(), "i"); // case-insensitive
    $button.show().filter(function() {
        return !re.test($(this).text());
    }).hide();   
});

基本上,每次用户键入输入以过滤元素时,您都希望运行该函数。您隐藏了与用户输入不匹配的所有按钮。