Issue
So I have created this website which lets users search for the weather in different cities. These searches then get saved in an object which looks like this through the localstorage.
To display this on the website I've tried to make the following
<div class="jumbotron bg-white">
<div class="container">
<h1>Latest requests</h1>
<h5 id="get-weather">We remember your five last requests for you :)</h5>
<div class="last-requests">
<img src="" class="imgs">
<p class="cityname" class="mr-3"></p>
<p class="cityweather"></p>
<p class="citytemp"></p>
<p class="citywind"></p>
</div>
</div>
</div>
And the following JS
// Displays last 5 requests/searches
function displayLastRequests() {
const lastReq = JSON.parse(localStorage.getItem('last-requests'))
console.log(lastReq)
if (displayLastRequests > 0) {
// for loop request
for (req in lastReq) {
$(".imgs").attr('src', req.imgurl);
$(".cityname").text(req.city_name);
$(".cityweather").text(req.city_weather);
$(".citytemp").text(req.city_temp + " °C");
$(".citywind").text(req.city_wind + " m/s");
}
}
};
displayLastRequests()
Not quite sure where I'm doing something wrong, any help would be much appreciated.
Solution
Your existing code will only show the last search as there's only one "cityname" to output to.
You can use HTML5 <template>
to provide a ...well... template which you can copy and add as required.
Your for
loop may also need to be for (.. of ..)
rather than .. in ..
which will give indexes rather than entries.
Updated code:
function displayLastRequests() {
//const lastReq = JSON.parse(localStorage.getItem('last-requests'))
// Sample data
const lastReq = [
{city_name:"Istanbul", weather:"Cloudy"},
{city_name:"Madrid", weather:"Stormy"},
{city_name:"London", weather:"Sunny"}
];
console.log(lastReq)
for (req of lastReq) {
var clone = $($("#last-request-template").html());
clone.appendTo(".last-requests");
clone.find(".cityname").text(req.city_name);
clone.find(".cityweather").text(req.weather);
//clone.find(".imgs").attr('src', req.imgurl);
//clone.find(".citytemp").text(req.city_temp + " °C");
//clone.find(".citywind").text(req.city_wind + " m/s");
}
};
displayLastRequests()
.last-requests { border: 1px solid #CCC; }
.last-request+.last-request { border-top: 1px solid #CCC; }
p { padding:5px; margin: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="jumbotron bg-white">
<div class="container">
<h1>Latest requests</h1>
<h5 id="get-weather">We remember your five last requests for you </h5>
<template id='last-request-template'>
<div class='last-request'>
<!--<img src="" class="imgs">-->
<p class="cityname"></p>
<p class="cityweather"></p>
<!--<p class="citytemp"></p>-->
<!--<p class="citywind"></p>-->
</div>
</template>
<div class="last-requests"> </div>
</div>
</div>
Answered By - freedomn-m Answer Checked By - Mary Flores (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.