[javascript] Creating a select box with a search option

I am trying to replicate what you can see here in this image. enter image description here

I want to be able to either type in the text field above the box or just click on the option directly.

What would be the best way to go about that? Is there anything bootstrap related that exists already?

This question is related to javascript jquery html css html-select

The answer is


This will work for most of us. The answer given by Hemanth Palle is the easiest way to do it, It worked for me and the JS code wasn't necessary. The only problem that I've found is that according to W3Schools, The datalist tag is not supported in Internet Explorer 9 and earlier versions, or in Safari.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<input list="browsers">
<datalist id="browsers">
  <option value="Internet Explorer">
  <option value="Firefox">
  <option value="Chrome">
  <option value="Opera">
  <option value="Safari">
</datalist>  
</body>
</html>

Full option searchable select box

This also supports Control buttons keyboards such as ArrowDown ArrowUp and Enter keys

_x000D_
_x000D_
function filterFunction(that, event) {_x000D_
    let container, input, filter, li, input_val;_x000D_
    container = $(that).closest(".searchable");_x000D_
    input_val = container.find("input").val().toUpperCase();_x000D_
_x000D_
    if (["ArrowDown", "ArrowUp", "Enter"].indexOf(event.key) != -1) {_x000D_
        keyControl(event, container)_x000D_
    } else {_x000D_
        li = container.find("ul li");_x000D_
        li.each(function (i, obj) {_x000D_
            if ($(this).text().toUpperCase().indexOf(input_val) > -1) {_x000D_
                $(this).show();_x000D_
            } else {_x000D_
                $(this).hide();_x000D_
            }_x000D_
        });_x000D_
_x000D_
        container.find("ul li").removeClass("selected");_x000D_
        setTimeout(function () {_x000D_
            container.find("ul li:visible").first().addClass("selected");_x000D_
        }, 100)_x000D_
    }_x000D_
}_x000D_
_x000D_
function keyControl(e, container) {_x000D_
    if (e.key == "ArrowDown") {_x000D_
_x000D_
        if (container.find("ul li").hasClass("selected")) {_x000D_
            if (container.find("ul li:visible").index(container.find("ul li.selected")) + 1 < container.find("ul li:visible").length) {_x000D_
                container.find("ul li.selected").removeClass("selected").nextAll().not('[style*="display: none"]').first().addClass("selected");_x000D_
            }_x000D_
_x000D_
        } else {_x000D_
            container.find("ul li:first-child").addClass("selected");_x000D_
        }_x000D_
_x000D_
    } else if (e.key == "ArrowUp") {_x000D_
_x000D_
        if (container.find("ul li:visible").index(container.find("ul li.selected")) > 0) {_x000D_
            container.find("ul li.selected").removeClass("selected").prevAll().not('[style*="display: none"]').first().addClass("selected");_x000D_
        }_x000D_
    } else if (e.key == "Enter") {_x000D_
        container.find("input").val(container.find("ul li.selected").text()).blur();_x000D_
        onSelect(container.find("ul li.selected").text())_x000D_
    }_x000D_
_x000D_
    container.find("ul li.selected")[0].scrollIntoView({_x000D_
        behavior: "smooth",_x000D_
    });_x000D_
}_x000D_
_x000D_
function onSelect(val) {_x000D_
    alert(val)_x000D_
}_x000D_
_x000D_
$(".searchable input").focus(function () {_x000D_
    $(this).closest(".searchable").find("ul").show();_x000D_
    $(this).closest(".searchable").find("ul li").show();_x000D_
});_x000D_
$(".searchable input").blur(function () {_x000D_
    let that = this;_x000D_
    setTimeout(function () {_x000D_
        $(that).closest(".searchable").find("ul").hide();_x000D_
    }, 300);_x000D_
});_x000D_
_x000D_
$(document).on('click', '.searchable ul li', function () {_x000D_
    $(this).closest(".searchable").find("input").val($(this).text()).blur();_x000D_
    onSelect($(this).text())_x000D_
});_x000D_
_x000D_
$(".searchable ul li").hover(function () {_x000D_
    $(this).closest(".searchable").find("ul li.selected").removeClass("selected");_x000D_
    $(this).addClass("selected");_x000D_
});
_x000D_
div.searchable {_x000D_
    width: 300px;_x000D_
    float: left;_x000D_
    margin: 0 15px;_x000D_
}_x000D_
_x000D_
.searchable input {_x000D_
    width: 100%;_x000D_
    height: 50px;_x000D_
    font-size: 18px;_x000D_
    padding: 10px;_x000D_
    -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */_x000D_
    -moz-box-sizing: border-box; /* Firefox, other Gecko */_x000D_
    box-sizing: border-box; /* Opera/IE 8+ */_x000D_
    display: block;_x000D_
    font-weight: 400;_x000D_
    line-height: 1.6;_x000D_
    color: #495057;_x000D_
    background-color: #fff;_x000D_
    background-clip: padding-box;_x000D_
    border: 1px solid #ced4da;_x000D_
    border-radius: .25rem;_x000D_
    transition: border-color .15s ease-in-out, box-shadow .15s ease-in-out;_x000D_
    background: url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'%3E%3Cpath fill='%23343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/%3E%3C/svg%3E") no-repeat right .75rem center/8px 10px;_x000D_
}_x000D_
_x000D_
.searchable ul {_x000D_
    display: none;_x000D_
    list-style-type: none;_x000D_
    background-color: #fff;_x000D_
    border-radius: 0 0 5px 5px;_x000D_
    border: 1px solid #add8e6;_x000D_
    border-top: none;_x000D_
    max-height: 180px;_x000D_
    margin: 0;_x000D_
    overflow-y: scroll;_x000D_
    overflow-x: hidden;_x000D_
    padding: 0;_x000D_
}_x000D_
_x000D_
.searchable ul li {_x000D_
    padding: 7px 9px;_x000D_
    border-bottom: 1px solid #e1e1e1;_x000D_
    cursor: pointer;_x000D_
    color: #6e6e6e;_x000D_
}_x000D_
_x000D_
.searchable ul li.selected {_x000D_
    background-color: #e8e8e8;_x000D_
    color: #333;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="searchable">_x000D_
    <input type="text" placeholder="search countries" onkeyup="filterFunction(this,event)">_x000D_
    <ul>_x000D_
        <li>Algeria</li>_x000D_
        <li>Bulgaria</li>_x000D_
        <li>Canada</li>_x000D_
        <li>Egypt</li>_x000D_
        <li>Fiji</li>_x000D_
        <li>India</li>_x000D_
        <li>Japan</li>_x000D_
        <li>Iran (Islamic Republic of)</li>_x000D_
        <li>Lao People's Democratic Republic</li>_x000D_
        <li>Micronesia (Federated States of)</li>_x000D_
        <li>Nicaragua</li>_x000D_
        <li>Senegal</li>_x000D_
        <li>Tajikistan</li>_x000D_
        <li>Yemen</li>_x000D_
    </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Use a data list instead.

<form action="/action_page.php" method="get">
      <input list="browsers" name="browser">
      <datalist id="browsers">
        <option value="Internet Explorer">
        <option value="Firefox">
        <option value="Chrome">
        <option value="Opera">
        <option value="Safari">
      </datalist>
      <input type="submit">
    </form>

Not supported I.E. 9 and back. https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_datalist


Selectize Js has all options we require .Please Try It

_x000D_
_x000D_
  $(document).ready(function () {_x000D_
      $('select').selectize({_x000D_
          sortField: 'text'_x000D_
      });_x000D_
  });
_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/js/standalone/selectize.min.js" integrity="sha256-+C0A5Ilqmu4QcSPxrlGpaZxJ04VjsRjKu+G82kl5UJk=" crossorigin="anonymous"></script>_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/css/selectize.bootstrap3.min.css" integrity="sha256-ze/OEYGcFbPRmvCnrSeKbRTtjG4vGLHXgOqsyLFTRjg=" crossorigin="anonymous" />_x000D_
</head>_x000D_
<body>_x000D_
  <select id="select-state" placeholder="Pick a state...">_x000D_
    <option value="">Select a state...</option>_x000D_
    <option value="AL">Alabama</option>_x000D_
    <option value="AK">Alaska</option>_x000D_
    <option value="AZ">Arizona</option>_x000D_
    <option value="AR">Arkansas</option>_x000D_
    <option value="CA">California</option>_x000D_
    <option value="CO">Colorado</option>_x000D_
    <option value="CT">Connecticut</option>_x000D_
    <option value="DE">Delaware</option>_x000D_
    <option value="DC">District of Columbia</option>_x000D_
    <option value="FL">Florida</option>_x000D_
    <option value="GA">Georgia</option>_x000D_
    <option value="HI">Hawaii</option>_x000D_
    <option value="ID">Idaho</option>_x000D_
    <option value="IL">Illinois</option>_x000D_
    <option value="IN">Indiana</option>_x000D_
  </select>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_


Select2 http://select2.github.io may be even better and more active than Chosen.

See this comparison: http://sitepoint.com/jquery-select-box-components-chosen-vs-select2

I went for Select2 (a few months ago) because Chosen had an issue when using Chinese characters via an IME http://github.com/harvesthq/chosen/issues/2663 It works great.


This will done by using jquery. Here is the code

<select class="chosen" style="width:500px;">
<option>Html</option>
<option>Css</option>
<option>Css3</option>
<option>Php</option>
<option>MySql</option>
<option>Javascript</option>
<option>Jquery</option>
<option>Html5</option>
<option>Wordpress</option>
<option>Joomla</option>
<option>Druple</option>
<option>Json</option>
<option>Angular Js</option>
</select>
</div>
<script type="text/javascript">
$(".chosen").chosen();
</script>

Working Example Here...


Here's a handy open source library I made earlier that uses jQuery: https://bitbucket.org/warwick/searchablelist/src/master/ And here is a working copy on my VPS: http://developersfound.com/SearchableList/ The library is highly customisable with overridable behavours and can have seperate designs on the same web page Hope this helps


I did my own version for bootstrap 4. If you want to use it u can check. https://github.com/AmagiTech/amagibootstrapsearchmodalforselect

_x000D_
_x000D_
amagiDropdown(
    {
        elementId: 'commonWords',
        searchButtonInnerHtml: 'Search',
        closeButtonInnerHtml: 'Close',
        title: 'Search and Choose',
        bodyMessage: 'Please firstly search with textbox below later double click the option you choosed.'
    });
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
<div class="form-group">
                <label for="commonWords">Favorite Word</label>
                <select id="commonWords">
                <option value="1">claim – I claim to be a fast reader, but actually I am average.</option><option value="2" selected>be – Will you be my friend?</option><option value="3">and – You and I will always be friends.</option>
                </select>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

<script src="https://rawcdn.githack.com/AmagiTech/amagibootstrapsearchmodalforselect/9c7fdf8903b3529ba54b2db46d8f15989abd1bd1/amagidropdown.js"></script>
_x000D_
_x000D_
_x000D_


This simple code worked for me

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<input list="brow">_x000D_
<datalist id="brow">_x000D_
  <option value="Internet Explorer">_x000D_
  <option value="Firefox">_x000D_
  <option value="Chrome">_x000D_
  <option value="Opera">_x000D_
  <option value="Safari">_x000D_
</datalist>  _x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Incase you need to use only select tag use Selectize Js. It has all options we require .Please Try It Demo using Selectize Js


You can use select2 . it is the best js for this job.
https://select2.org/dropdown

_x000D_
_x000D_
$(document).ready(function () {_x000D_
//change selectboxes to selectize mode to be searchable_x000D_
   $("select").select2();_x000D_
});
_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
  <select id="select_page" style="width:200px;" class="operator"> _x000D_
         <option value="">Select a Page...</option>_x000D_
         <option value="alpha">alpha</option> _x000D_
         <option value="beta">beta</option>_x000D_
         <option value="theta">theta</option>_x000D_
         <option value="omega">omega</option>_x000D_
  </select>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to html-select

How can I get new selection in "select" in Angular 2? How to show disable HTML select option in by default? Remove Select arrow on IE Bootstrap 3 select input form inline Change <select>'s option and trigger events with JavaScript How to use a Bootstrap 3 glyphicon in an html select Creating a select box with a search option Drop Down Menu/Text Field in one How to have a default option in Angular.js select box How to set the 'selected option' of a select dropdown list with jquery