Adding eventlisteners iteratively not working.
I have an array that I'm trying to iterate through to add to a list. Everything but the eventlistener works fine.
let suggestion;
for (let i = 0; i < cities.length; i++) {
suggestion = document.createElement('li');
suggestion.innerHTML =
${cities[i].postcode} - ${cities[i].city};
suggestion.dataset.city = cities[i].city;
suggestion.dataset.id = cities[i].location;
suggestion.addEventListener('click', () => {
input.value = suggestion.dataset.city;
input.dataset.id = suggestion.dataset.id;
closeList(input);
});
suggestions.appendChild(suggestion);
}
The problem is, regardless of which li item is clicked afterwards, the last in the list is added to the input, and I can't figure out why.
Any suggestions?3 Replies