I have a HTML file where I have to enter some data in a form. The data should be added into a item:
<div id="recipe-list">
<h2>Recipes</h2>
<ul id="recipes"></ul>
</div>
I have to implement a function to add and display the data from the form into the unordered list. This is such function:
function addRecipe(recipe) {
const {title, ingredients, instructions} = recipe;
if (title && ingredients && instructions) {
recipes.push(recipe);
displayRecipes();
}
}
And this is the function to display every new set of data entered:
function displayRecipes() {
// Write your code here for task 3
const recipesList = document.getElementById('recipes');
recipesList.innerHTML = '';
for (const recipe of recipes) {
const recipeItem = document.createElement('li');
const optionButtons = document.createElement('li');
const deleteButton = document.createElement('button')
deleteButton.textContent = 'Delete';
deleteButton.addEventListener("click", deleteRecipe(recipes[1]));
recipeItem.innerText =
`${recipe.title}
Ingredients: ${recipe.ingredients}
Instructions: ${recipe.instructions}
`
optionButtons.append(deleteButton);
recipesList.appendChild(recipeItem);
recipesList.appendChild(optionButtons);
}
}
Every new set of data should also come with a Delete button which of course requires a delete function. This is the delete Function:
function deleteRecipe(index){
if (index >= 0 && index < recipes.length) {
recipes.splice(index, 1); // Remove 1 element at the specified index
displayRecipes();
console.log(recipes)
clearInputFields();
isEditMode = false;
}
}
I already managed to display all the data such as title, ingredients and instructions but I’m stuck at the Delete button. I can’t figure out how to make it work so that I can delete the entire item entered into the unordered list.
Can anybody help?