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
Jochem
Jochem2y ago
can you try moving let suggestion into the for loop? So just let suggestion = document...
Nox
NoxOP2y ago
that solved it, and I think I understand why, even - thanks! :)
Jochem
Jochem2y ago
nice! Glad to help
Want results from more Discord servers?
Add your server