loading...

Autocomplete Dropdown using native HTML

blacksonic profile image Gábor Soós ・1 min read

You have probably seen dropdowns with autocomplete ability in jQuery, React, Vue, etc. Most of us would assume it is only possible with the help of Javascript. But is it possible without Javascript? Yes, it is! I came across an HTML element that is supported by browsers and does the same.

The secret element is the datalist element. If we attach a datalist to an already existing input element we get a native dropdown with autocomplete! Booom, and it just works 🚀

Plus it is supported by all modern browsers.

<input list="europe-countries" placeholder="Start typing...">
<datalist id="europe-countries">
  <option>Russia</option>
  <option>Germany</option>
  <option>United Kingdom</option>
  ...
</datalist>

The input starts behaving like a select and when we start typing it searches inside the options of the datalist.

Let's see it in action!

Incredible 🦄

Posted on by:

blacksonic profile

Gábor Soós

@blacksonic

Enthusiastic full-stack JavaScript developer/lead, tech writer, speaker at Emarsys

Discussion

pic
Editor guide
 

try this.


<input list="europe-countries" placeholder="Start typing..." type="email" multiple>

Basically on pressing comma you can view the drop-down again and select from the list.

 

Tried ,, ., ; on Waterfox Classic and chrome (yuck) and no success, are you sure it works?

 

One problem - at least depending on the use case - with this is, that it allows to send other values than those specified in the list. F.ex. imagine a UI to configure the listening IP for a daemon where the available options would be populated by the IPs available on the host. With a regular select the user can only choose valid options, whereas the datalist-solution allows him to enter and submit a custom value, which could be invalid. Obviously the server side should handle such cases. But I still think this is important to know.

 

I tried this code but it doesn't drop down . Can you help me out ?

 

Which browser?

 

I'm using bracket editor on GoogLe chrome

 

Thanks for this post, Gábor!
It's amazing!

 
 

I felt the same...is this some kind of sorcery? 🧙‍♂️

 
 

Not working in FF for Android... (Or not working as intended)

It doesn't draw autocomplete dropdown, but when you press Enter, it selects first matching variant

 

On chrome mobile it seems fine...you click it and no dropdown?

 

Thanks for sharing Useful Information!!