I am trying to create a basic weather app with HTML & JS
If i call getWeather("insert any city Name") in the console it works.
But when i put the name of the city in my input and hit "Go", i don’t get anything returned on the webpage.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weather</title>
</head>
<body>
<h1 class="city">Weather in</h1>
<h3 class="temperature">Temperature: </h3>
<h3 class="humidity">Humidity: </h3>
<form action="">
<label for="">City Name</label>
<input class="cityInput" type="text">
<button type="submit" class="submit-button">Go</button>
</form>
<script src="index.js" ></script>
</body>
Javascript
function getWeather(city){
const apiKey = "https://api.openweathermap.org/data/2.5/weather?q=" + city +"&appid= + "API_KEY" + &units=metric#"
fetch(apiKey)
.then((response) => response.json())
.then((data) => displayWeather(data));
}
function displayWeather (data){
const city = data.name
const temp = data.main.temp
const humidity = data.main.humidity
console.log(city, temp, humidity);
document.querySelector(".city").innerHTML = "Weather in " + city;
document.querySelector(".temperature").innerHTML = "Temperature is " + temp;
document.querySelector(".humidity").innerHTML = "Humidity is " + humidity + " %";
}
function search () {
getWeather(document.querySelector(".cityInput").value);
}
document.querySelector(".submit-button").addEventListener("click", function () {
search();
});
>Solution :
The only issue I can see in your code is the submit event. Usually when submit button is clicked will cause the page to refresh. I think your code is working but then page refreshed that’s why you don’t get the results.
To fix that modify the last line to:
document
.querySelector(".submit-button")
.addEventListener("click", function(e) {
e.preventDefault();
search();
});
This will prevent the form submission and allow the data to be returned.