Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Event listener not returning data to html for weather app

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<!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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading