DEV Community

Antonio Salvati 🦊
Antonio Salvati 🦊

Posted on

Searchable Select 🤔

The Select

The HTML select element is super useful, but sometime we need somthing more powerful, when we have hundreds of options (eg. a list of all the world's countries) it would be nice to let the user to be able to filter the elements, unluckily we don't have a searchable or filterable attribute for it

<label for="country">Please select your country</label>
<select id="country" name="country" required>
  <option value="it">Italy<option>
  <option value="fr">France<option>
  ... and so many other options ...
<select>

The Input

A way to search elements inside a list with native HTML elements is with an input plus datalist

<label for="country">Please select your country</label>
<input id="country" name="country" required list="country-list" />
<datalist id="country-list">
  <option value="Italy">
  <option value="France">
  ...
</datalist>

In this way we have an input with hints, but the user can still write anything he want.
So we need to validate it!

The Validation

Let's use the pattern attribute to validate the input

<label for="country">Please select your country</label>
<input id="country" name="country" required list="country-list"
  pattern="Italy|France" title="Please select a country" />
<datalist id="country-list">
  <option value="Italy">
  <option value="France">
  ...
</datalist>

Cool, now we have an Input with searchable options, and only the defined ones are allowed!

The problem

The only problem I see here is that it is not very clear at first glance that it is not a normal text input, but a (let me say it) searchable select.

Only after a user interaction the dropdown will be shown.

Conclusions

HTML give us many tools, let's see if we can use and combine them before build our own solutions 😃

Let me know what do you think about this approach!

Top comments (0)