60

How can I implement a select-style drop down menu in HTML with an option that is a text input?

The idea being that someone can either select from a list of predefined options, or input their own option.

jesal
  • 7,852
  • 6
  • 50
  • 56

1 Answers1

142

You can use input text with "list" attribute, which refers to the datalist of values.

<input type="text" name="city" list="cityname">
    <datalist id="cityname">
      <option value="Boston">
      <option value="Cambridge">
    </datalist>

This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist

Mehadi Hassan
  • 1,160
  • 1
  • 13
  • 33
Oleg
  • 2,165
  • 1
  • 15
  • 7
  • 4
    Hi Oleg, the original poster asked for either a plugin or some sample code - could you flesh out your answer to show how to apply the "list" attribute to do what they want? Thank you. – Wai Ha Lee Apr 20 '15 at 18:17
  • 7
    woah. Now I have just learnt something new. I think not many programmers know this simple trick to solve the problem. Thank you. –  Aug 20 '15 at 07:35
  • 3
    Datalist do the trick, but the display on some browsers (chrome for ex) can become problematic. Contrarily to select element, you cannot style or even simlply have a scrollbar which is a big issue for long lists. – Vincent Teyssier Jan 08 '16 at 09:31
  • 11
    It's not supported at all in Safari. http://www.w3schools.com/tags/tag_datalist.asp – PeterM Feb 03 '16 at 20:49
  • 1
    This is a nice plugin that makes data list cross-platform: http://projects.sergiodinislopes.pt/flexdatalist/ – jesal Jan 15 '17 at 00:47
  • 2
    Is there a way to open the select box with only one click. Currently it can be opened if i click twice on the input field or click the down arrow. – CraZyDroiD Jun 23 '17 at 05:38
  • can we have same feature with + (increment) - (decrement) option selector with open amount also ? not a dropdown – Ajwad Syed Jul 18 '19 at 07:57
  • The problem with this is that the user needs to click the input element twice in order for the list to appear. It would be incredible if there was an option to have the list appear on the first click or whenever the input element has focus. – default123 Dec 03 '20 at 14:13