Guide to creating a search-enabled dropdown menu

Recently, I created a dropdown menu using Bootstrap.

The code I used can be found here: 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>

Now, I am looking to enhance my dropdown by adding a search box inside it. This will allow users to type and filter the options in the dropdown list.

After trying various methods, including using external plugins like Select2, I encountered an issue. These plugins require dropdowns to be coded using <select> and <option> tags. However, my dropdown is built using buttons and the built-in Bootstrap dropdown class.

If anyone has any suggestions or solutions, please help me out.

Answer №1

Whenever I need to organize lists, my go-to tool is list.js. Check out this solution using a Bootstrap-4 dropdown with a filterable list:

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: Refer to Example 5 in the list.js documentation for setting up 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;
}

Explore the Bootstrap 4 documentation for dropdowns to learn about using <button> elements in dropdowns.

Answer №2

Big shoutout to everyone who assisted, I was able to crack the code. Sharing my solution here for those in need.

function displayResults() {
    var input, filter, list, item, anchor, x;
    input = document.getElementById("searchInput");
    filter = input.value.toUpperCase();
    list = document.getElementById("resultsList");
    item = list.getElementsByTagName("li");
    for (x = 0; x < item.length; x++) {
        anchor = item[x].getElementsByTagName("a")[0];
        if (anchor.innerHTML.toUpperCase().indexOf(filter) > -1) {
            item[x].style.display = "";
        } else {
            item[x].style.display = "none";
        }
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sorting after grouping in AngularJS is a breeze

After using lodash.js groupBy to organize my collection, the order is correct when I log it with console.debug. However, when I try to display it in the UI using ng-repeat, the ordering gets messed up. var list = [{id:1,categoryId:1,name:test1}, ...

Is it possible that the passing of Form Serialize and list to the controller is not functioning properly?

i am struggling with the following code in my controller: public ActionResult SaveWorkOrder(DTO_WorkOrder objWork, List<DTO_PartsWO> listTry) { //something } here is my model : public class DTO_WorkOrder { public string Id { get; set; ...

"The TextInput component in ReactNative is preventing me from inputting any text

Experiencing issues with the iOS and Android simulators. Upon typing, the text disappears or flickers. I attempted initializing the state of the texts with preset values instead of leaving them empty. However, this caused the TextInput to stick to the ini ...

Extract the price value from the span element, then multiply it by a certain number before adding it to a div element

On the checkout page of my website, I have the following HTML: <tr class="order-total"> <th>Total</th> <td><strong><span class="woocommerce-Price-amount amount"> <span class="w ...

Why does the text in a div display in Safari 8.2 and Chrome 39, but not in Firefox 34?

In my HTML document, I have a div tag located within the body like so: <div id="content_text"></div>​ Using javascript, I later set the contents of the div like this: var content_text = document.getElementById("content_text") c ...

Conceal or reveal buttons using JavaScript

I am struggling with a function that is supposed to hide certain buttons and create a new button. When I click on the newly created button, it should make the previously hidden buttons visible again. However, the function does not seem to work properly. ...

My function handler is not being triggered when using React's onClientClick

I'm facing an issue with a button component I have, let's refer to it as < MyButton >. <MyButton onClick={this.props.calculate} onClientClick={this.changeColor} > Calculate </MyButton> Whenever I click the button, my cal ...

Issue with Videogular: hh:mm:ss Date filter not functioning properly

I am currently working on integrating Videogular into my audio player application. Below are the settings provided in the example code on this particular page: <vg-time-display>{{ currentTime | date:'mm:ss' }}</vg-time-display> ...

What is the procedure for deactivating a plugin within the replace feature of CkEditor?

Is there a way to disable image-upload on specific CKEditor textareas without affecting all of them through the config.js file? I'm wondering if it's possible to achieve this using the .replace method. For example: CKEDITOR.replace("meTextarea" ...

Outlining in Three.js

Can I achieve a black outline effect on my 3D models using three.js? I'm looking to create graphics similar to Borderlands 2, with toon shading and distinct black outlines. ...

Firefox and Internet Explorer do not support the functionality of HTML5 <audio> tags

My radio stream player code works perfectly on Chrome and iOS Safari, but I'm facing compatibility issues with Firefox and Internet Explorer 11. Here's a snippet from my index.php file: <script type="text/javascript" src="http://code.jquery. ...

Is there a notification system that sparkles like a precious Facebook gem

Is there a system similar to Facebook's request, message, and notification bubble system that can alert users on their profiles about new messages or notifications? I know Facebook is very advanced, but if anyone knows of something similar, please let ...

Challenges regarding variable scope in JavaScript

Presented below is the JavaScript code I am currently using, which involves jQuery: function language(language) { var text = new Object(); $.ajax({ type: "GET", url: "includes/xml/languages/" + language + ".xml", dataType: ...

What methods can be used to block direct attribute updates in a JS/TS class?

class Creature { secretProperty modifySecretProperty(value) { this.secretProperty = value } } new Creature().modifySecretProperty('hidden way') //success new Creature().secretProperty = 'not permitted' // failure To r ...

To close modal A in ReactJS using React-Bootstrap after opening modal B from modal A, follow these steps:

When the registration button is clicked, a signup modal appears. Is there a way to then open a login modal from within the signup modal, ensuring that the signup modal closes once the login modal pops up? show={this.props.signupModalOn} onHide={this.props. ...

Can a menu with data-toggle='dropdown' remain visible even after clicking on it?

I have a dropdown menu that I created with the use of data-toggle='dropdown'. Everything seems to be working fine as the buttons close the menu upon clicking, except I would like the gray button (as shown below) to keep the menu open. https://i. ...

Switch or toggle between colors using CSS and JavaScript

Greetings for taking the time to review this query! I'm currently in the process of designing a login form specifically catered towards students and teachers One key feature I'm incorporating is a switch or toggle button that alternates between ...

AngularJS showcases the full spectrum of available methods

I am struggling to create a method for composing a URL in my class. Here is what I have attempted: The createLink method takes an ID and returns the corresponding URL: console.log("before the method"); console.log($scope.createLink ) $scope.createLink = f ...

React Material UI Table - All switches toggled simultaneously

I recently integrated a react mat ui table into my application and included switches in one of the columns. However, I am encountering an issue where all the switches toggle together instead of independently. Any suggestions on how to resolve this? < ...

Ways to swap webpack-dev-server for alternative servers such as express or apache

After using vue-cli to scaffold a Vue app, I am looking to set up a new web server instead of webpack-dev-server. I am interested in having a separate configuration file to customize the server settings, similar to using Node Express for production deploym ...