🛠️ Typeahead: Selecting a prediction

Hey ,

I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.

Please upgrade (use this link) access this content.

I'm super eager to help you learn more!

🛠️ Typeahead: Selecting a prediction

If the user clicks a prediction, we want to replace the input value with the prediction.

Replace input field with chosen item.

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
})
Replace input's value with selected prediction

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)
})
Closes the prediction list when user selects an item.

That’s it!