99

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?

Mahdi Bashirpour
  • 17,147
  • 12
  • 117
  • 144
SBB
  • 8,560
  • 30
  • 108
  • 223

15 Answers15

111

This simple code worked for me

<input list="brow">
<datalist id="brow">
  <option value="Internet Explorer">
  <option value="Firefox">
  <option value="Chrome">
  <option value="Opera">
  <option value="Safari">
</datalist>  

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

biberman
  • 5,606
  • 4
  • 11
  • 35
Hemanth Palle
  • 2,053
  • 1
  • 9
  • 11
  • 4
    This allows the user to type in anything, not just the options provided. Also requires double click to open the dropdown list. – HomeIsWhereThePcIs Jun 18 '20 at 07:14
  • 1
    @HomeIsWhereThePcIs - Yes , In that case , I suggest SelectJs, I am using it in my appplications & its great. – Hemanth Palle Jun 18 '20 at 18:56
  • 8
    @HomeIsWhereThePcIs - To be fair, if it *didn't* allow you to type in anything, it'd become a game of "guess the next correct letter that matches something in the list". In that scenario, I don't believe the user would understand why the keys they're typing do not display in the input. It would actually seem very broken. – Aaron Cicali Mar 22 '21 at 19:28
  • 2
    Is this feature HTML 5? because u didnt need Jquery – Oscar May 18 '21 at 16:01
81

Selectize Js has all options we require .Please Try It

  $(document).ready(function () {
      $('select').selectize({
          sortField: 'text'
      });
  });
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<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>
<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" />
</head>
<body>
  <select id="select-state" placeholder="Pick a state...">
    <option value="">Select a state...</option>
    <option value="AL">Alabama</option>
    <option value="AK">Alaska</option>
    <option value="AZ">Arizona</option>
    <option value="AR">Arkansas</option>
    <option value="CA">California</option>
    <option value="CO">Colorado</option>
    <option value="CT">Connecticut</option>
    <option value="DE">Delaware</option>
    <option value="DC">District of Columbia</option>
    <option value="FL">Florida</option>
    <option value="GA">Georgia</option>
    <option value="HI">Hawaii</option>
    <option value="ID">Idaho</option>
    <option value="IL">Illinois</option>
    <option value="IN">Indiana</option>
  </select>
</body>
</html>
Hemanth Palle
  • 2,053
  • 1
  • 9
  • 11
  • Is there a way to upon selecting the right option there results can be posted – Kehlin Swain Dec 08 '20 at 18:46
  • Seems cool, but can anyone explain why I see when I inspect the field in the code runner? I don't see in the sample code above, only select and option. I must be missing something. Thanks. – Kreidol Aug 31 '22 at 21:07
  • Hello I have on click event set to my select field when I use your code + on click event only first option is being shown rest all being hidden, any workaround to have onlick event + search function? is my code – dh47 Jul 05 '23 at 10:26
26

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.

Kai Carver
  • 2,240
  • 29
  • 23
  • I totally agree with you. Not only it supports all languages, but also the container is not relatively positioned, which means it's compatible with any theme. I tried Chosen and because of a stupid `position:relative` parent it failed to work. – Javid Apr 05 '17 at 05:02
21

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

$(document).ready(function () {
//change selectboxes to selectize mode to be searchable
   $("select").select2();
});
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>

</head>
<body>
  <select id="select_page" style="width:200px;" class="operator"> 
         <option value="">Select a Page...</option>
         <option value="alpha">alpha</option> 
         <option value="beta">beta</option>
         <option value="theta">theta</option>
         <option value="omega">omega</option>
  </select>
</body>
</html>
majed
  • 467
  • 4
  • 7
19

Full option searchable select box

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

function filterFunction(that, event) {
    let container, input, filter, li, input_val;
    container = $(that).closest(".searchable");
    input_val = container.find("input").val().toUpperCase();

    if (["ArrowDown", "ArrowUp", "Enter"].indexOf(event.key) != -1) {
        keyControl(event, container)
    } else {
        li = container.find("ul li");
        li.each(function (i, obj) {
            if ($(this).text().toUpperCase().indexOf(input_val) > -1) {
                $(this).show();
            } else {
                $(this).hide();
            }
        });

        container.find("ul li").removeClass("selected");
        setTimeout(function () {
            container.find("ul li:visible").first().addClass("selected");
        }, 100)
    }
}

function keyControl(e, container) {
    if (e.key == "ArrowDown") {

        if (container.find("ul li").hasClass("selected")) {
            if (container.find("ul li:visible").index(container.find("ul li.selected")) + 1 < container.find("ul li:visible").length) {
                container.find("ul li.selected").removeClass("selected").nextAll().not('[style*="display: none"]').first().addClass("selected");
            }

        } else {
            container.find("ul li:first-child").addClass("selected");
        }

    } else if (e.key == "ArrowUp") {

        if (container.find("ul li:visible").index(container.find("ul li.selected")) > 0) {
            container.find("ul li.selected").removeClass("selected").prevAll().not('[style*="display: none"]').first().addClass("selected");
        }
    } else if (e.key == "Enter") {
        container.find("input").val(container.find("ul li.selected").text()).blur();
        onSelect(container.find("ul li.selected").text())
    }

    container.find("ul li.selected")[0].scrollIntoView({
        behavior: "smooth",
    });
}

function onSelect(val) {
    alert(val)
}

$(".searchable input").focus(function () {
    $(this).closest(".searchable").find("ul").show();
    $(this).closest(".searchable").find("ul li").show();
});
$(".searchable input").blur(function () {
    let that = this;
    setTimeout(function () {
        $(that).closest(".searchable").find("ul").hide();
    }, 300);
});

$(document).on('click', '.searchable ul li', function () {
    $(this).closest(".searchable").find("input").val($(this).text()).blur();
    onSelect($(this).text())
});

$(".searchable ul li").hover(function () {
    $(this).closest(".searchable").find("ul li.selected").removeClass("selected");
    $(this).addClass("selected");
});
div.searchable {
    width: 300px;
    float: left;
    margin: 0 15px;
}

.searchable input {
    width: 100%;
    height: 50px;
    font-size: 18px;
    padding: 10px;
    -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
    -moz-box-sizing: border-box; /* Firefox, other Gecko */
    box-sizing: border-box; /* Opera/IE 8+ */
    display: block;
    font-weight: 400;
    line-height: 1.6;
    color: #495057;
    background-color: #fff;
    background-clip: padding-box;
    border: 1px solid #ced4da;
    border-radius: .25rem;
    transition: border-color .15s ease-in-out, box-shadow .15s ease-in-out;
    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;
}

.searchable ul {
    display: none;
    list-style-type: none;
    background-color: #fff;
    border-radius: 0 0 5px 5px;
    border: 1px solid #add8e6;
    border-top: none;
    max-height: 180px;
    margin: 0;
    overflow-y: scroll;
    overflow-x: hidden;
    padding: 0;
}

.searchable ul li {
    padding: 7px 9px;
    border-bottom: 1px solid #e1e1e1;
    cursor: pointer;
    color: #6e6e6e;
}

.searchable ul li.selected {
    background-color: #e8e8e8;
    color: #333;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="searchable">
    <input type="text" placeholder="search countries" onkeyup="filterFunction(this,event)">
    <ul>
        <li>Algeria</li>
        <li>Bulgaria</li>
        <li>Canada</li>
        <li>Egypt</li>
        <li>Fiji</li>
        <li>India</li>
        <li>Japan</li>
        <li>Iran (Islamic Republic of)</li>
        <li>Lao People's Democratic Republic</li>
        <li>Micronesia (Federated States of)</li>
        <li>Nicaragua</li>
        <li>Senegal</li>
        <li>Tajikistan</li>
        <li>Yemen</li>
    </ul>
</div>
Mahdi Bashirpour
  • 17,147
  • 12
  • 117
  • 144
11

You can achieve this without JavaScript using pure HTML Datalist element:

<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>

References:

noraj
  • 3,964
  • 1
  • 30
  • 38
5

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>
SammeAyala
  • 79
  • 1
  • 4
  • 1
    As of Safari 12.1, released 2019-03-25, now supports the `datalist` tag. https://en.wikipedia.org/wiki/Safari_version_history#Safari_12 – James Mazikowski Sep 25 '19 at 18:55
4

If you want to reach your goal with only vanilla js, then I strongly recommend to use Tom Select library which is forked from Selectize.js and then decoupled from jQuery.

    new TomSelect("#select-state",{
        create: false,
        sortField: {
            field: "text",
            direction: "asc"
        }
    });
<html>
<head>
    <link href="https://cdn.jsdelivr.net/npm/tom-select@2.0.0-rc.4/dist/css/tom-select.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/tom-select@2.0.0-rc.4/dist/js/tom-select.complete.min.js"></script>
</head>
<body>
  <select id="select-state" placeholder="Pick a state...">
    <option value="">Select a state...</option>
    <option value="AL">Alabama</option>
    <option value="AK">Alaska</option>
    <option value="AZ">Arizona</option>
    <option value="AR">Arkansas</option>
    <option value="CA">California</option>
    <option value="CO">Colorado</option>
    <option value="CT">Connecticut</option>
    <option value="DE">Delaware</option>
    <option value="DC">District of Columbia</option>
    <option value="FL">Florida</option>
    <option value="GA">Georgia</option>
    <option value="HI">Hawaii</option>
    <option value="ID">Idaho</option>
    <option value="IL">Illinois</option>
    <option value="IN">Indiana</option>
  </select>
</body>
</html>
3

$(document).ready(function () {
//change selectboxes to selectize mode to be searchable
   $("select").select2();
});
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>

</head>
<body>
  <select id="select_page" style="width:200px;" class="operator"> 
         <option value="">Select a Page...</option>
         <option value="alpha">alpha</option> 
         <option value="beta">beta</option>
         <option value="theta">theta</option>
         <option value="omega">omega</option>
  </select>
</body>
</html>

This was good solution but, only problem is, its inefficient for large data

  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/31413214) – AFOC Apr 01 '22 at 04:05
0

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

user2288580
  • 2,210
  • 23
  • 16
0

If you want to reach your goal with a few updates in your code just do the following

     <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" />
    <!-- Be sure to put the links in the right position to avoid dependency issue.-->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <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>

<script>
    $(document).ready(function () {
        $('select').selectize({
            sortField: 'text'
        });
    });

  // to clear the selected value.
   $('form').find('.selectized').each(function(index, element) { element.selectize && element.selectize.clear() })

 </script>
0

To anyone still finding this, you'll also want to consider Select2, which does all this easily. https://select2.org/getting-started/installation

Jeremy L.
  • 853
  • 8
  • 15
0

Here is a simple solution without any plugins. Only html and some jquery. You can save following code sample as a html file and test it.

function myFunction() {
  $("#dropdown-values").addClass("show");
}

$(document).click(function(e) {
  if( e.target.id != 'myInput') {
    $("#dropdown-values").removeClass("show");
  }
});

function filterFunction() {
  var input, filter, a, i;
  filter = $("#myInput").val().toUpperCase();
  div = document.getElementById("myDropdown");
  a = div.getElementsByTagName("a");
  for (i = 0; i < a.length; i++) {
    txtValue = a[i].textContent || a[i].innerText;
    if (txtValue.toUpperCase().indexOf(filter) > -1) {
      a[i].style.display = "";
    } else {
      a[i].style.display = "none";
    }
  }
}

function setValueOfInput(e) {
    $("#myInput").val(e.innerHTML);
}
.dropdown-content {
  position: absolute;
  background-color: #f6f6f6;
  overflow: auto;
}

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

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

.show {display: block !important;}

.dropdown-values{
    display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h2>Dropdown with search</h2>

<div class="dropdown">
  <div id="myDropdown" class="dropdown-content">
    <input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()" onclick="myFunction()">
    <div id="dropdown-values" class="dropdown-values">
        <a onclick="setValueOfInput(this)">option 1</a>
        <a onclick="setValueOfInput(this)">option 2</a>
        <a onclick="setValueOfInput(this)">option 3</a>
        <a onclick="setValueOfInput(this)">option 4</a>
        <a onclick="setValueOfInput(this)">option 5</a>
    </div>
  </div>
</div>
Sathsara AM
  • 69
  • 1
  • 4
-1

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

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.'
    });
<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/popper.js@1.16.1/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>
garg10may
  • 5,794
  • 11
  • 50
  • 91
-6

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>
Zoe
  • 27,060
  • 21
  • 118
  • 148
M. Lak
  • 903
  • 9
  • 18
  • 4
    Not really by jQuery, mostly by extension named chosen.js – szymeo Mar 17 '18 at 19:32
  • This uses select instead of input datalist, so it loses the search functionality – James Bond May 11 '20 at 22:07
  • @JamesBond im not sure if you checked the example link .. but this provides the search and select functionality. :) BTW i was in search something like this. got multiple choices now to select. THANKS – Jahanzeb Nawaz Jun 04 '20 at 17:14