I am creating a weather dashboard for an assignment in school but I am having issues with the last little bit. Basically, the user will search for a specific city and in return will get all data and information regarding the weather for that city. What I am currently stuck on is figuring out how to properly use event.target.value. When the user searches for a city, I append the name of the city to my webpage and convert the name into a button. Once the button is clicked, I want it to return just the name of the city. However, I get what seems to be an empty string or it is not recognizing the value it is targeting? Below is my code :
let cities = [];
function saveCity() {
event.preventDefault();
let city = $('.form-control').val().trim()
cities.push(city)
$("#newCity").append('<ul><button class="btn btn-primary">' + city + '</button></ul>');
localStorage.setItem("cities", JSON.stringify(cities))
}
function appendStorage(){
cities = JSON.parse(localStorage.getItem('cities'));
for (let index = 0; index < cities.length; index++) {
const element = cities[index];
$("#newCity").append('<ul><button class="btn btn-primary">' + element +
'</button></ul>');
}
$(".cities").click(function(event) {
let cityName = event.target.value
console.log('clicked')
console.log(cityName)
})
}
$(".cities").click(function(event) {
let cityName = event.target.value
console.log(cityName)
})
If i remove '.value' from the 'event.target' and search for the weather in the city of 'London' for example and 'console.log'
$(".cities").click(function(event) {
let cityName = event.target
console.log(cityName)
})
I get a console.log of :
<button class="btn btn-primary">London</button>
I can further explain if what I am asking is not clear or I can upload more code if need be. Thanks for any help.
Usually, you attach a value to input, select, textarea elements, basically user input elements and fetch it using .value.
It is possible to add value to a button using the value attribute, which is missing in your case.
Use $(event.target).text() for getting button text
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With