I’m trying to use a button to get seven random objects and put them as elements in HTML. I want it to be able to be used multiple times in succession. The function always works the first time, but when I try to use it a second time the variables still have the same value as they did in the end of the function. Excuse any bad coding practices I’m self-taught and just recently started. This project is an attempt at something slightly higher level.
//Test Meals
addMeal('test1','this is a test','testing');
addMeal('test2','this is a test','testing');
addMeal('test3','this is a test','testing');
addMeal('test4','this is a test','testing');
addMeal('test5','this is a test','testing');
addMeal('test6','this is a test','testing');
addMeal('test7','this is a test','testing');
Meals is an array of these test objects.
//Function to pick a meal for each day of the week
function getWeek () {
let tempMeals = meals;
let total = meals.length;
let tempPicked;
let picked = [];
for (let i=0; i < 7; i++) {
tempPicked = tempMeals[Math.floor(Math.random() * total)];
picked.push(tempPicked);
index = tempMeals.indexOf(tempPicked);
tempMeals.splice(index,1);
total -= 1;
}
return picked;
}
//Function to get meals on button click
function pushMeals () {
let picked = getWeek();
for (i=0;i<1;i++) {
for (let j=0;j<3;j++){
if (j === 0) {
days[i][j].innerHTML = picked[i].name;
}
else if (j === 1) {
days[i][j].innerHTML = picked[i].ingredients;
}
else if (j === 2) {
days[i][j].innerHTML = picked[i].directions;
}
else {
days[i][j].innerHTML = 'There is an error. Try again.'
}
}
}
}
getMeals.addEventListener('click',pushMeals);