I am new to stackOverflow, although I have browsed the forums for help in the past. However, this time I couldn't find a solution to my current issue, so I decided to create an account and seek assistance.
The problem at hand is related to a workout application that consists of 3 pages - page 1: where the user selects gym equipment (bike, rower or x trainer) and difficulty level, page 2: displays specific workouts based on the selections, and page 3: the actual workout to be completed.
My goal is to store certain data in a localStorage object depending on the link clicked by the user. But, each time a link is clicked, only the last value in the 'for in' loop gets stored, regardless of the link. Here's a simplified explanation:
PAGE 1: User selects equipment and difficulty from dropdown menus
// Constructor function to create workout instances
function Workout(name, desc, loc, work_rest, res, intensity){
// ... properties defined here
}
// Create Workouts for bike
var bike = {
easy: [
{workout_1: new Workout('Tabata', 'This is a tabata style workout', '../Workout_page_example/index.html', [20, 10,...])},
{workout_2: new Workout('Classic_HIIT', 'This is a HIIT session', '../Workout_page_example/index.html',[60,30,...])},
{workout_3: new Workout('Clock_Face', 'Beat the clock', '../Workout_page_example/index.html',[120, 60...])}
],
int:[],
adv:[]
};
btn.addEventListener('click', function() {
if(equipment.value === "bike"){
if(difficulty.value === "easy"){
localStorage.setItem('get_info', JSON.stringify(bike.easy));
} else if(difficulty.value === "int"){
localStorage.setItem('get_info', JSON.stringify(bike.int));
} else if(difficulty.value === "adv"){
localStorage.setItem('get_info', JSON.stringify(bike.adv));
}
location.href = 'workouts/index.html';
});
This above page is working fine. Now, moving on to Page 2 which displays all available workouts based on the user's previous selections:
PAGE 2: Display workouts based on equipment and difficulty selected
window.addEventListener('load', function(){
var getInfo = JSON.parse(localStorage.getItem('get_info'));
var dom = document.getElementById('section');
for(var key in getInfo){
var obj = getInfo[key];
for(var prop in obj){
// display workout details
dom.innerHTML += "<hr/><div class='workout_title'><h1>"+obj[prop].name.replace('_',' ')+"</h1></div>";
dom.innerHTML += "<div class='workout_desc'><h4>"+obj[prop].desc+"</h4></div>";
// store data in localStorage
localStorage.setItem('work_rest', JSON.stringify(obj[prop].work_rest));
localStorage.setItem('resistance', JSON.stringify(obj[prop].res));
localStorage.setItem('intensity', JSON.stringify(obj[prop].intensity));
dom.innerHTML += "<div class='workout_link'><a href='"+ obj[prop].loc +"' id='"+obj[prop].name+"'>START >></a></div>";
}
}
})
On clicking the links, only the data for the 'Clock Face' instance is being stored in the localStorage object. I understand why this is happening but unsure how to fix it.