DEV Community

Cover image for Autocomplete like a boss!
Jordan Finneran
Jordan Finneran

Posted on • Updated on • Originally published at jordanfinners.dev

Autocomplete like a boss!

Contents

  1. Intro
  2. Datalist
  3. Example
  4. Summary

Intro

Often, we need to help a user search or look for something that is domain specific to your application.
Enter autocomplete!

I've seen this done many, many, many different ways. Please no more <span>s!

Datalist

Enter datalist, this provides a set of recommended options for the user to choose from.
This list can be hardcoded to a specific set, or you can load in your own dynamically!

Datalists are great because they handle matching the users input against the results and you can add options from API results too.

You link this to an input element via the list attribute.

One thing to note there is also the browsers autocomplete, e.g. where Chrome (or your browser of choice) remembers your text input, this can be controlled using the autocomplete attribute on the input. You can disable it, or use it to your advantage. Check it out here.

This one is definitely easier to do by example, so let's jump in.

Example

Shut up and show me the code.

<label>Choose a browser from this list:
<input list="browsers" name="choice" />
</label>
<datalist id="browsers">
  <option value="Chrome">
  <option value="Firefox">
  <option value="Internet Explorer">
  <option value="Opera">
  <option value="Safari">
  <option value="Microsoft Edge">
</datalist>
Enter fullscreen mode Exit fullscreen mode

You can see how easy it is to do! Try it out here.

A common use case is for search which is also really easy to achieve. You can see an interactive example below.
We use a search type input, and when the user types we go off an do some work to return some results. In this case just search an array but this could be a request to an API or database etc.

Summary

In summary, you can use what browsers give you to create your own search and autocomplete!
As with all native HTML elements, it means less bytes shipped to the client.
It also means accessibility will be handled by the browsers which is normally best.

It works across all browsers, so give it go! Get searching! :D

Happy building!

Top comments (0)