Adding a search feature to HTML5 select

16,839

Solution 1

Use <datalist> element

<label for="cars">Search cars: <input list="cars" name="cars" type="text">
</label>
<datalist id="cars">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</datalist>

Solution 2

Batter You use <datalist> in stand of the <select>

<input placeholder="Type Car Name" list="cars">
 <datalist id="cars">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
 </datalist>

Note : The datalist tag is not supported in Internet Explorer 9 and earlier versions, or in Safari.

Share:
16,839
jarvan
Author by

jarvan

Updated on June 26, 2022

Comments

  • jarvan
    jarvan almost 2 years
    <select>
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="mercedes">Mercedes</option>
      <option value="audi">Audi</option>
    </select> 
    

    I need to add a search bar that will allow me to filter the unwanted options from the list. I need to use select and I need to do this without a plugin, what's the easiest way to do this? I tried using the select2 plugin, but it screwed up my entire application, because it depended on some logic written by a previous developer. The data population is already taken care of, so I don't need to do anything to populate it.

    I also need to point out that I need to be able to type inside the textbox, something which html5 select doesn't allow me to do and be able to have a dropdown arrow that allows me to see the full list. Can we do it with html5 alone through some trick, or I need a lot of javascript to do this?

  • jarvan
    jarvan almost 8 years
    Is there a way to maintain the select tag and somehow add a drop arrow in there without too much javascript or none at all? I knew about datalist, but I needed to keep the select attribute to make it work proper.
  • guest271314
    guest271314 almost 8 years
    @jarvan What is purpose of using <select> element? Yes, it is possible. You could also use <ul>, <li> elements, retrieve .textContent or dataset of element for a value
  • jarvan
    jarvan almost 8 years
    I need to keep it to make the application work, because there's a jQuery selector that uses select to retrieve data.
  • guest271314
    guest271314 almost 8 years
    "because there's a jQuery selector that uses select to retrieve data" Can you include javascript at Question?
  • jarvan
    jarvan almost 8 years
    Sorry, I added the javascript tag, because I couldn't really word the question right with the word javascript in there.