如何制作可搜索的下拉菜单

5

我使用了Bootstrap制作了一个下拉菜单。

我参考的代码在这里:http://getbootstrap.com/docs/4.0/components/dropdowns/

<div class="dropdown">
  <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Dropdown button
  </button>
  <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
    <a class="dropdown-item" href="#">Action</a>
    <a class="dropdown-item" href="#">Another action</a>
    <a class="dropdown-item" href="#">Something else here</a>
  </div>
</div>

现在我想在下拉列表中添加一个搜索框,这样人们可以输入内容,它会缩短到更合适的下拉列表。我尝试了很多方法,其中一些使用像Select2这样的外部插件,但是它们需要使用

您想让下拉列表根据搜索字段中的输入进行筛选吗?还是您在将输入字段放入下拉列表时遇到了问题? - Martin Lindgren
是的,我希望下拉列表可以根据输入的搜索筛选。 - Jake Lam
这个问题与Jira有什么关系? - Maitrey684
2个回答

1
当我想要对列表进行排序时,我使用list.js。 以下是一个示例,展示如何通过Bootstrap-4下拉菜单实现具有可过滤列表的问题解决方案:

https://jsfiddle.net/o9b17p2d/29/

HTML:

<div class="dropdown">
  <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Dropdown
  </button>
  <div class="dropdown-menu" aria-labelledby="dropdownMenu2" id="dropdown-sorted-list">
    <ul class="dropdown-menu-list list">
      <li>
        <button class="dropdown-item dropdown-item-name" type="button">Action</button>
      </li>
      <li>
        <button class="dropdown-item dropdown-item-name" type="button">Another action</button>
      </li>
    </ul>
    <input type="text" class="form-control dropdown-item search" placeholder="Filter" aria-label="Filter" aria-describedby="basic-addon1">
  </div>
</div>

JS: 请参考list.js文档中的示例5,了解如何设置list.js。
$(document).ready(function() {
  var options = {
    valueNames: ['dropdown-item-name']
  };

  var hackerList = new List('dropdown-sorted-list', options);
});

CSS:
.dropdown-menu-list {
  list-style-type: none;
  padding-left: 0;
}

正如您可以在Bootstrap 4文档中的下拉菜单中阅读到的那样,可以在下拉菜单中使用<button>元素。

他正在寻求可搜索的下拉菜单。 <input type="search"> 并且列表应该在 keypresskeyup 事件上作为下拉菜单出现,只有与输入字符串匹配的列表才应该出现。 - Shashi Ranjan

1

感谢大家的帮助,我已经找到了解决方案。我会在这里发布给任何需要的人。

function searchBox() {
    var input, filter, ul, li, a, i;
    input = document.getElementById("myInput");
    filter = input.value.toUpperCase();
    ul = document.getElementById("myUL");
    li = ul.getElementsByTagName("li");
    for (i = 0; i < li.length; i++) {
        a = li[i].getElementsByTagName("a")[0];
        if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
            li[i].style.display = "";
        } else {
            li[i].style.display = "none";

        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接