I have a drop-down when i select the city from the option, weather data will be fetch through API, my issue is when i select option previous data cannot be remove. In this below screenshot 1st i selected city (KARACHI) api return the data on the screen accurately, when i select Islamabad only Islamabad weather data should be display. How can i overcome this issue.
$(document).ready(function() {
$("select.select_city").change(function() {
var selectedCountry = $(this).children("option:selected").val();
// alert("You have selected the country - " + selectedCountry);
// var cityy = "Lahore";
$.getJSON("http://api.openweathermap.org/data/2.5/weather?q=" + selectedCountry + "&units=metric&APPID=d89208ad904d31a4402384ff1d4d1a2f",
function(data) {
console.log(data);
var icon = "https://openweathermap.org/img/w/" + data.weather[0].icon + ".png";
$('.icon').attr("src", icon);
// console.log(icon);
var temp = Math.round(data.main.temp);
$('.temp').append(temp);
var weather = data.weather[0].main;
// console.log(weather);
$('.weather').append(weather);
var city = data.name;
// console.log(city);
$('.city').append(city);
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="weather-container" style="background:#ccc;text-align:center">
<img src="" alt="" class="icon">
<p class="city"></p>
<p class="weather" style="font-size: 22px;margin:0"></p>
<p class="temp" style="font-size: 60px;margin:0;font-weight:bold"></p>
<select name="" class="select_city" id="">
<option value="Lahore">Lahore</option>
<option value="Karachi">Karachi</option>
<option value="Islamabad">Islamabad</option>
<option value="Perth">Perth</option>
<option value="Berlin">Berlin</option>
</select>
</div>
Consider writing a seperate function to get the data based on city and call it in dropdown's
change()
function, also you would want to use.html()
instead of.append()
: