What is the best way to incorporate a search bar into a dropdown menu?

Would someone be able to assist me in adding a search bar as the primary value of the dropdown menu? I am using ASP.NET MVC and this is my current code snippet.

<div class="col-md-8">
    <div class="dropdown">
         <div class="chzn-dd-width">
               @Html.DropDownListFor(
                   model => model.DriverId, 
                   Model.Drivers, 
                   new { @id = "driverDropDown", @class = " form-control chosen-search" })
          </div>
     </div>
</div>

Answer №1

Hello Ravindu Saluwadana,

Have you given this a shot? Check out this solution for adding search functionality on DropDownListFor

@Html.DropDownListFor(x =>
    x.StockCode,
    (IEnumerable<SelectListItem>)ViewBag.AllStockList,
    new
    {
        @class = "form-control selectpicker",
        @Value = @Model.Description,
        onchange = "this.form.submit();",
        data_show_subtext="true",
        data_live_search="true"
})

Answer №2

function displayDropdown() {
    document.getElementById("myDropdown").classList.toggle("show");
}

function filterItems() {
    var input, filter, div, a;
    input = document.getElementById("myInput");
    filter = input.value.toUpperCase();
    div = document.getElementById("myDropdown");
    a = div.getElementsByTagName("a");
    for (var i = 0; i < a.length; i++) {
        if (a[i].innerHTML.toUpperCase().indexOf(filter) > -1) {
            a[i].style.display = "";
        } else {
            a[i].style.display = "none";
        }
    }
}
.dropbtn {
    background-color: #4CAF50;
    color: white;
    padding: 16px;
    font-size: 16px;
    border: none;
    cursor: pointer;
}

.dropbtn:hover, .dropbtn:focus {
    background-color: #3e8e41;
}

#myInput {
    border-box: box-sizing;
    background-image: url('searchicon.png');
    background-position: 14px 12px;
    background-repeat: no-repeat;
    font-size: 16px;
    padding: 14px 20px 12px 45px;
    border: none;
    border-bottom: 1px solid #ddd;
}

#myInput:focus {outline: 3px solid #ddd;}

.dropdown {
    position: relative;
    display: inline-block;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f6f6f6;
    min-width: 230px;
    overflow: auto;
    border: 1px solid #ddd;
    z-index: 1;
}

.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
}

.dropdown a:hover {background-color: #ddd;}

.show {display: block;}
    <!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">

</head>
<body>

<div class="dropdown">
<button onclick="displayDropdown()" class="dropbtn">Dropdown</button>
  <div id="myDropdown" class="dropdown-content">
    <input type="text" placeholder="Search.." id="myInput" onkeyup="filterItems()">
    <a href="#about">item test</a>
    <a href="#base">soheil</a>
    <a href="#blog">bijavar</a>
    <a href="#contact">php</a>
    <a href="#custom">Hello</a>
    <a href="#support">Support</a>
    <a href="#tools">Tools</a>
  </div>
</div>


</body>
</html>

Answer №3

One option is to utilize a third-party plugin that supports multiple dropdowns, like multiselect, with updated styles and search functionality.

A recommended plugin for this purpose is the SELECT2 Dropdown Plugin.

Visit https://select2.org/searching for more information.

Answer №4

Implement this feature by adding the attribute data_live_search="true" to your dropdownlistfor.

In order to enable this functionality, you will need to include the following scripts:

1.bootstrap-select.min.js
2.boostrap-select.min.css

You can download these files from the following link -

For example, you can use the code snippet below:

<div class="col-md-8">
    <div class="dropdown">
         <div class="chzn-dd-width">
              @Html.DropDownListFor(
                model => model.DriverId, 
               Model.Drivers, 
               new { @id = "driverDropDown", @class = " form-control chosen-search" ,data_live_search="true"})
      </div>
 </div>

If you have any questions or concerns, feel free to reach out. I hope this information is helpful!

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

Nullify the unfulfilled fetch call

When a value is entered in the search bar on the webpage, it gets added to a URL and used to retrieve JSON data. Everything works smoothly, but if a value is inputted that the API doesn't have information for, a null response is returned. The questio ...

Send the data to be placed in the div to launch the window

I'm attempting to open a new window within the same tab and transfer some html code to be inserted into a specific div section of the newly opened window. However, I'm encountering difficulties in passing the data as illustrated below: JavaScrip ...

Having difficulty converting an object into an iterable using an arrow function

Currently immersed in learning JavaScript, I successfully created a class and now find myself faced with the task of making it iterable. The Group class represents a collection of values, akin to a Set, equipped with methods for adding, removing, and che ...

iOS devices will not scroll horizontally if there is a div that scrolls vertically within a div that scrolls horizontally

Picture a div that scrolls horizontally, housing two vertical-scrolling divs. You'll need to scroll left and right to navigate, then up and down inside the inner divs to read the content. /* RESET TO MINIMUM */ body, html { height: 100%; mar ...

Changing the dynamic boundaries does not produce any results in the 'react-leaflet' library

Encountered an issue while trying to utilize the react-leaflet's bounds property. In my scenario, the application has predefined initial bounds in the state (referred to as fallback bounds) which are passed during the first component render. The archi ...

Error: Webpack is unable to load PDF file: Module parsing unsuccessful. A suitable loader is required to manage this file format

I am relatively new to using webpack for my projects. Recently, I wanted to incorporate a feature that involved displaying PDFs. After some research, I came across the "react-pdf" library and decided to give it a try. While everything worked smoothly in a ...

A single Modal, Ajax, and data that is continuously refreshed

I'm currently facing a challenge in my project as I try to implement Ajax functionality. Although I'm relatively new to using it, I believe I have a basic understanding of its workings. My website involves collecting form data, posting it to a d ...

Implementing asynchronous code when updating state using React hooks

Here's a scenario I'm dealing with: const [loading, setLoading] = useState(false); ... setLoading(true); doSomething(); // <--- at this point, loading remains false. Since setting state is asynchronous, what would be the best approach to ...

Is there a method to run code in the parent class right after the child constructor is called in two ES6 Parent-Child classes?

For instance: class Parent { constructor() {} } class Child { constructor() { super(); someChildCode(); } } I need to run some additional code after the execution of someChildCode(). Although I could insert it directly there, the requirement is not to ...

Holding off on routing the pathName through the router until the next-page-transitions have been completed

In my current setup, I have two distinct elements at play. Using the code snippet below: className={router.pathname.startsWith("/pagename") ? "menu-active" : ""} I am able to apply the menu-active class to the pagename naviga ...

I am experiencing a JSON parse error while making an AJAX request after upgrading to Codeigniter 3.x. What could be the reason behind this

I am currently in the process of updating my Codeigniter framework from version 2.2.6 to 3.0.6, and unfortunately, this update has caused some previously working code to break. One specific error that I am encountering is "SyntaxError: JSON.parse: unexpect ...

The request for JSON parsing encountered a failed attempt, resulting in an error while trying to parse the JSON

var userData = { "emailAddress": document.getElementById('emailAddress').value, "password": document.getElementById('password').value } var userDataString = JSON.stringify(userData); alert(userDataString); var url = "url"; var ...

How to Access a PHP Variable within a JavaScript Function Argument

.php <?php $timeArray = [355,400,609,1000]; $differentTimeArray = [1,45,622, 923]; ?> <script type="text/javascript"> var i=0; var eventArray = []; function generateArray(arrayName){ eventVideoArray = <?php echo json_encode(arrayName); ...

What is the process for creating custom command settings for each specific Discord server or guild?

If the server admin writes "!setprefix $" the bot will change its prefix from "!" to "$", but this change will only apply to that specific server. ...

Guide on sending a JavaScript variable to PHP using AJAX

I am currently utilizing the following JavaScript code to obtain data from a td element when a button is clicked within an onclick event. function rfk(element) { var element = element.parentElement.parentElement; var id = parseInt(element.childre ...

Display Content in a DIV When Form Field is Unfocused

After hours of searching, I still haven't found a solution! I am trying to create a form field (text) where users can type in text. I want the text they enter to appear in a div on the screen either as they type or after they finish typing. Maybe thi ...

Retrieving an Element that Triggered an HTTP GET Request in Node.js with Express

In my Express front-end development project, I have a table with rows containing links that trigger GET requests. These requests are sent to the back-end, which is created using node.js, in order to retrieve files corresponding to each row. All links follo ...

The POST method in Node JS request-promises does not properly handle string inputs

When I am trying to establish a connection between my node.js module and another server, I utilize the 'request-promise' library. My implementation for posting data looks like this: rp.({ method: 'POST', headers:{ 'Conte ...

The ability to retrieve variables within a certain scope from a function that is declared externally

Is there a method to access and print the value of a closure variable, temp, from a function defined outside the closure but referenced within it without passing temp as an argument to the function? var funcA, funcB; funcA = function () { console.log( ...

What could be the reason for the unexpected undefined value of my ajaxurl variable?

Seeking assistance with implementing code to track mp3 plays in a Wordpress plugin using ajax-counter.js jQuery(document).ready(function($) { console.log(ChurchAdminAjax.ajaxurl); $("audio").bind("play", function(){ console.log(ChurchAdmin ...