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));
}
CodePudding user response:
If you're adding so many buttons use event delegation. Add one listener to the parent container, add your buttons, and then, in the listener function, check to see if the clicked element is a button, and log its value.
const searchHistory = document.querySelector('#searchHistory');
// Add one listener to the container that calls `handleClick`
searchHistory.addEventListener('click', handleClick, false);
function handleClick(e) {
// Destructure the nodeName and value from
// the clicked element, and log the value if the
// element is a button
const { nodeName, value } = e.target;
if (nodeName === 'BUTTON') {
console.log(value);
}
}
function recentSearch(city) {
var addCity = document.createElement('button');
addCity.value = city;
addCity.textContent = city;
searchHistory.append(addCity);
}
const cities = ['London', 'Rome', 'New York', 'Seoul', 'Kingston'];
for (const city of cities) {
recentSearch(city);
}
<div id="searchHistory"></div>
CodePudding user response:
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));
}
CodePudding user response:
Try using data-attributes. They make your code easier to read and provide a great way to pass along data inside of elements - and you can access their data using element.dataset.<attribute_name>
- in this case e.target.dataset.value
(from within the buttons click listener).
cities = []
function recentSearch(city) {
// FOR DEMO ONLY::
if (!city) city = "city " Math.ceil(Math.random() * 1000);
var addCity = document.createElement("button");
addCity.setAttribute("data-value", city);
addCity.textContent = city;
addCity.addEventListener('click', e => {
console.log(`my city is: ${e.target.dataset.value}`);
})
document.getElementById("searchHistory").append(addCity);
cities.push(city);
// localStorage.setItem("searches",JSON.stringify(cities));
}
<div id='searchHistory'>
</div>
<button onclick='recentSearch()'>Make City</button>