Search code examples
javascriptjqueryspring-mvcjstl

Displaying data on different card view


I am displaying weather data for each city on a card on button click

JSP page

 <c:forEach var="list" items="${listHist}">
            <div class="w3-container">
             <ul class="w3-ul w3-card-4">
             <li class="w3-bar">
             <span onclick="this.parentElement.style.display='none'" class="w3-bar-item w3-button w3-white w3-xlarge w3-right">×</span>
          <img src="resources/assets/images/a1.png" class="w3-bar-item w3-circle w3-hide-small" style="width:85px">
           <div class="w3-bar-item">
            <span><font size="6">Name : ${list.name}</font></span><br>
            <span>
            <ul><li class="card-text">Ticket Number : ${list.ticketNo}
                        <li class="card-text">From : ${list.fromCity}
                        <li class="card-text">To : ${list.toCity}
                        <li class="card-text">Date : ${list.travelDate}
                        <li class="card-text">Travel Class : ${list.travelClass}
                        <li  class="card-text">Gender : ${list.gender}
                        <li  class="card-text">Passenger type : ${list.ptype}
                        <li  class="card-text">Price : ${list.price}
                            <p id="weatherdata"></p>    
                        </li>
                        </ul>
                        </span>
                <font color="white"><button type="button" class="btn btn-danger" onclick="currWeather(&quot;${list.toCity}&quot;);myFunction();" style="margin-left: 0px ">Weather</button></font>
            </div>
        </div>
        </c:forEach>

My script: I have used jquery weather script where yahoo api has been used to fetch weather data for that city

function currWeather(city){

     var city =city;
      $(document).ready(function() {

               $.simpleWeather({
                 location: city+', IN',
                 woeid: '',
                 unit: 'c',
                 success: function(weather) {                       
                         $("p").slideToggle();
                        /*  $("div") */
                           document.getElementById("weatherdata").innerHTML=weather.code+" "+weather.temp+ " "+weather.units.temp+" "+weather.currently;
                 },
                 error: function(error) {
                     document.getElementById("weatherdata").innerHTML=error;
                 }
               });
             });

  }

Problem: The data from the function is always displayed on the first card, even if the button on other cards are pressed. I want to display the weather data individually on each card after clicking on the button.


Solution

  • try using an index or a name <p id="weatherdata_#{loop.count}"></p> or even <p id="weatherdata_${list.name}"></p>

    Use that unique id in the script