I'm getting JSON data from weather API. Currently my code gets town name from an html input and queries the API to get weather for that particular place. I have introduced a select element for country codes (so if you want to check the weather in Naples USA rather than Naples Italy you have to select the US code in the dropdown menu). I want it to check if there has been a country code selected before firing off the search, and if so add that into the parameters of the query.
I have tried some if/else statements with no success. The country codes are stored in an object and aren't hard-coded. Im getting the object from different API. I have managed to put those codes into the select element, but now I need to make sure the search considers if a different country region has been selected.
I would like the region variable to take in the country code, if user has selected one
// CODE THAT ADDS WEATHER DATA INTO DOM //
$("#weather-button").click(function() {
$(".weather-img").html("");
$(".weather-type").html("");
$(".weather-temp").html("");
var city = $("input[name=city-box]").val();
var region = "";
$.getJSON("https://api.openweathermap.org/data/2.5/weather?q=" + city + region + "&units=metric&myapikey", function(data) {
console.log(data);..........................
});
// HOW IM GETTING COUNTRY CODE DATA //
var countryCodes = [];
$.getJSON("https://restcountries.eu/rest/v2/all", function(countryData) {
var countryCodes = countryData.reduce((countries, item) => {
countries[item.name] = item.alpha2Code;
return countries;
}, {});
console.log(countryCodes);
// HOW IVE ADDED COUNTRY CODE DATA TO THE <SELECT> //
var selectBox = $("#country-select");
var select = document.getElementById("country-select");
selectBox.append($('<option>', {
value: -1,
text: 'Select a Country'
}));
for (index in countryCodes) {
select.options[select.options.length] = new Option(countryCodes[index], index);
}
})
})