For this Typeahead, we want to help users search for a country. If they enter J into the Typeahead, we show countries that begin with J.
A list of countries
To predict what users are typing, you need a list of possible choices. Since weāre helping users type a country, we need to have a list of countries in the world.
And we have this list already. You can find it in your JavaScript file.
We need to get what the user typed immediately after they type into the input field. Here, we can use the input event.
const typeahead = document.querySelector('.typeahead')
const input = typeahead.querySelector('input')
input.addEventListener('input', event => {
// Get what the user typed
})
Weāll use the value property to get what the user typed. Weāll also use trim to remove any whitespace thatās present.
input.addEventListener('input', event => {
// Get what the user typed
const input = event.target
const inputValue = input.value.trim()
console.log(inputValue)
})
Filtering the list of countries
If the user typed J into the Typeahead. We want to show a list of countries that begin with J. Here, we have Jamaica, Japan, Jersey, and Jordan.
We can use startsWith to check if a country starts with J. startsWith lets you check whether a string starts with the string you specified.
You can get the array by running matches through a map function. In the map function, weāll extract the countryās name from each country object. And we will wrap them inside <li> element.