Search code examples
javascripthtmljqueryopenweathermap

How to call javascript function multiple times?


I am using an API from OpenWeatherMap on my website to show weather condition of just some specific places only, altogether in one page. Here's the code:

<script src="https://code.jquery.com/jquery-3.0.0.js"></script>


<body>
  <input type="hidden" name="name" value="dehradun" id="cityName">
  <button onclick="getWeather()">Get weather of Dehradun</button>

  <div class="weatherResponse"></div>
  <br><br>

  <input type="hidden" name="name" value="pune" id="cityName">
  <button onclick="getWeather()">Get weather of Pune</button> '
  <div class="weatherResponse"></div>
  <br><br>

  <script>
    function getWeather() {
      $('.weatherResponse').html('');
      var cityName = $('#cityName').val();
      var apiCall = 'http://api.openweathermap.org/data/2.5/weather?q=' + cityName + '&mode=json&units=metric&appid=<apikey>';
      $.getJSON(apiCall, weatherCallback);

      function weatherCallback(weatherData) {
        var cityName = weatherData.name;;
        var country = weatherData.sys.country;
        var description = weatherData.weather[0].description;
        var temp = weatherData.main.temp;

        $('.weatherResponse').append("The Weather in " + cityName + " " + country + " is currently " + description + " with temperature: " + temp);
      }
    }
  </script>
</body>

Suppose if i want to show weather condition of two places using the same Javascript function then its showing the same result for both the places(Of place (Dehradun) mentioned first in code).

Help me solve this problem.


Solution

  • You can Pass both your city name and div (display results) as function parameter

     function getWeather(cityName, className)
     {
     
      $('.'+className+'').html('');
    
      var apiCall= 'http://api.openweathermap.org/data/2.5/weather?q=' + cityName + '&mode=json&units=metric&appid=d3d913fca612366a61837ea39a622480';
      $.getJSON(apiCall,weatherCallback);
    
      function weatherCallback(weatherData)
      {
        var cityName= weatherData.name;;
        var country= weatherData.sys.country;
        var description= weatherData.weather[0].description;
        var temp= weatherData.main.temp;
    
         $('.'+className+'').append("The Weather in " + cityName + " " + country + " is currently " + description + " with temperature: " + temp);
      }
    }
    <script src="https://code.jquery.com/jquery-3.0.0.js"></script>
    
    <body>
    <button onclick="getWeather('dehradun','wr1')">Get weather of Dehradun</button>
    <br><br>
    <div class="wr1"></div>
    <br><br>
    <button onclick="getWeather('pune','wr2')">Get weather of Pune</button>
    <br><br>
    <div class="wr2"></div>
    <br>
    </body>