CodePanda CodePanda - 5 months ago 8
Javascript Question

Remove old data on button click using jquery

So the problem I am facing is every time I click the submit button ajax will add

$(function (){
var $temp = $('#numberTemp');
var $namex = $('#cityName');
var $description = $('#description');
var $wind = $('#wind');
var $cloudiness = $('#cloudiness');
var $humidity = $('#humidity');
var $pressure = $('#pressure');
var $mintemp = $('#mintemp');
var $maxtemp = $('#maxtemp');

$('#submitbtn').click(function(){
var location = $('#inputtxt').val();
$.ajax({
type: 'GET',
url: "http://api.openweathermap.org/data/2.5/weather?q="+location+"&units=",
success: function(data){
$temp.append('<h2>'+data.main.temp+'</h2>');
$namex.append('<h2>'+data.name+'</h2>');
$description.append('<p>'+data.weather[0].description+'</p>');
$wind.append('<td>'+data.wind.speed+'</td>');
$cloudiness.append('<td>'+data.weather[0].main+'</td>');
$humidity.append('<td>'+data.main.humidity+'</td>');
$pressure.append('<td>'+data.main.pressure+'</td>');
$mintemp.append('<td>'+data.main.temp_min+'</td>');
$maxtemp.append('<td>'+data.main.temp_max+'</td>');
}

});
});
});

/**
$.each(data,function(index, data){
if (index === "main") {
$temp.append('<h2>'+data.temp+'</h2>');
}

});
**/


I want it to reset with new data every time I click the submit button. Any way I can do this?

Answer

All you need is replacing new value instead of just appending it. So use .html() function rather than .append() function:

$(function (){
    var $temp = $('#numberTemp');
    var $namex = $('#cityName');
    var $description = $('#description');
    var $wind = $('#wind');
    var $cloudiness = $('#cloudiness');
    var $humidity = $('#humidity');
    var $pressure = $('#pressure');
    var $mintemp = $('#mintemp');
    var $maxtemp = $('#maxtemp');

    $('#submitbtn').click(function(){
        var location = $('#inputtxt').val();
        $.ajax({
            type: 'GET',
            url: "http://api.openweathermap.org/data/2.5/weather?q="+location+"&units=",
            success: function(data){
                $temp.html('<h2>'+data.main.temp+'</h2>');
                $namex.html('<h2>'+data.name+'</h2>');
                $description.html('<p>'+data.weather[0].description+'</p>');
                $wind.html('<td>'+data.wind.speed+'</td>');
                $cloudiness.html('<td>'+data.weather[0].main+'</td>');
                $humidity.html('<td>'+data.main.humidity+'</td>');
                $pressure.html('<td>'+data.main.pressure+'</td>');
                $mintemp.html('<td>'+data.main.temp_min+'</td>');
                $maxtemp.html('<td>'+data.main.temp_max+'</td>');
            }

        });
    });
});