# Autocomplete in JavaScript

We are now implementing autocompletion. This term refers to a drop-down tooltip when entering text into an input. Let's look at an example. Below I made an input in which you can enter the name of the country. At the same time, if you enter some letters, then a list of countries that begin with the entered string will appear under the input.

If you wish, you can, in order not to enter the entire name of the country, click on any country and it will appear in the input. For this, in general, autocompletion is necessary. In the example, for simplicity, I made only three countries: Belarus, Belgium and Bulgaria. Enter the English character `'B'` into the input below, and then `'e'` and see what happens:

## Discussion

Let's discuss how to solve the problem. You need to make an array with the countries names. I have it like this:

`let arr = ['Belarus', 'Belgium', 'Bulgaria'];`

When entering text into the input, you need to run through the array with countries after each character entered and get the countries that start with the entered string. It is convenient to do this using the methods `filter` and `startsWith`.

With `filter` you can get an array of countries starting with the input string. Then you need to loop through this array and fill the list `ul` with li-items with countries. And so you need to do for each character input, first removing the previously created li-items from ul-list.

For your convenience, here is the finished layout:

`<div id="parent"> <input id="elem"> <ul id="list"></ul> </div> text text text text text` `#parent { position: relative; } #elem { padding: 5px; font-size: 18px; } #parent ul { position: absolute; margin: 0; padding: 0; list-style-type: none; background-color: white; } #parent li { border: 1px solid gray; font-size: 18px; padding: 5px; } #parent li:hover { border: 1px solid black; cursor: pointer; }`

Copy the provided HTML and CSS codes. Implement auto-completion according to the described algorithm.

← →
↑
en ru