I know this should be easy but I have spent hours trying to get this to work.
I am getting back JSON data from a weather api based on zip code. I want the zip code to come from and input(see below). However, when I use document.getElementById('city').value; I keep getting an error message in the console. What am I doing wrong? I know where the problem area is but i'm not sure how to fix it?
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Weather API</title>
<!-- <link rel="stylesheet" type="text/css" href="styles.css"> -->
<script src="main.js"></script>
</head>
<style>
li { list-style-type: none; }
.buffer { padding: 0.5rem 0; }
</style>
<body>
<p>My API call for weather</p>
<div class="buffer">
<input name="city" type="text" id="city" />
<button id="submit" onclick="weatherHistory();">Submit</button>
</div>
<div id='blank'> </div>
</body>
</html>
JS
const api = 'http://api.openweathermap.org/data/2.5/weather?';
const city = document.getElementById('city').value; // PROBLEM HERE
const input = 'zip=' + city + ',us';
const api_key = '&APPID= my-key-here';
const units = '&units=imperial';
var url = api + input + api_key + units;
function get(url) {
return new Promise((resolve, reject) => {
const req = new XMLHttpRequest();
req.open('GET', url);
req.onload = () => req.status === 200 ? resolve(req.response) : reject(Error(req.statusText));
req.onerror = (e) => reject(Error(`Network Error: ${e}`));
req.send();
});
}
function weatherHistory() {
get(url)
.then((data) => {
const x = JSON.parse(data);
const max = x.main.temp_max;
const min = x.main.temp_min;
const humidity = x.main.humidity;
var div = document.getElementById('blank');
const api_data = "<li> Min Temp: " + min + "</li>" + "<li> Max Temp: " + max + "</li>" + "<li>Humidity: " + humidity + "</li>"
div.innerHTML = api_data;
})
.catch((err) => {
console.log('Oops something went wrong, please try again');
});
}