How can I get the value of a button when there are many multiple buttons created? Currently on my Javascript file I have it so my search history makes a button in a list with a "value" of the city that is labeled.
When I click on the button that was made I get undefined.
function recentSearch(city) {
var addCity = document.createElement("button");
addCity.setAttribute("value", city);
addCity.textContent = city;
document.getElementById("searchHistory").append(addCity);
cities.push(city);
localStorage.setItem("searches",JSON.stringify(cities));
}
>Solution :
The following code will log the value of the button to the console when it is clicked.
function recentSearch(city) {
var addCity = document.createElement("button");
addCity.setAttribute("value", city);
addCity.textContent = city;
addCity.onclick = (e)=>{
console.log(e.target.getAttribute('value'));
//or whatever other code you want to do onclick
}
document.getElementById("searchHistory").append(addCity);
cities.push(city);
localStorage.setItem("searches",JSON.stringify(cities));
}