0

Can someone please tell me why my code doesn't work? In particular, clicking on the option does not work

let apiUrl = 'https://jsonplaceholder.typicode.com/todos'; // for test
let input = document.querySelector('.address');
let dataList = document.querySelector('#suggestions');

input.addEventListener('input', e => {
  let fragment = document.createDocumentFragment();
  fetch(apiUrl)
    .then(response => response.json())
    .then(addresses => {
      addresses.forEach(address => {
        console.log(address.title);
        let option = document.createElement('option')
        option.setAttribute('value', address.title);
        option.addEventListener('click', e => console.log('Hi!'))
        fragment.append(option);
      })
    })
    
  dataList.innerHTML = '';
  dataList.append(fragment);
});
<input class="address" type="text" list="suggestions">
<datalist id="suggestions"></datalist>
  • You are doing -> `dataList.append(fragment);` this before you have fetched. – Keith Mar 01 '22 at 16:30
  • Problem don't with options, I get options, options displayed when input, but I want to add event listener for options. – Najmubadr Mar 02 '22 at 14:36

0 Answers0