If the user clicks a prediction, we want to replace the input value with the prediction.
To do this, we listen for a click event on the <ul> element. (Event delegation pattern).
const ul = typeahead.querySelector('ul')ul.addEventListener('click', event => { if (!event.target.matches('li')) return})We want to get the name of the country in the <li>. We can get the name with textContent.
ul.addEventListener('click', event => { // ... const li = event.target const countryName = li.textContent console.log(countryName)})Then, we replace the input fieldโs value with the countryโs name.
ul.addEventListener('click', event => { // ... input.value = countryName})
The list of predictions is redundant now since the user has made a choice. Weโll hide the list.
ul.addEventListener('click', event => { // ... ul.setAttribute('hidden', true)})
Thatโs it!
Welcome! Unfortunately, you donโt have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson