Reputation: 55
I’m attempting to write JavaScript for recipe cards. I thought that using an object constructor would be the best because I’m creating multiple recipes with the same criteria. I need to use an array for the ingredients, but I can’t seem to make it work. The only thing that will show up is the recipe name, and the array comes back undefined.
I’m extremely new to JS, so please break things down for me like a child, while also being kind :)
Also, I apologize that the code is written this way. I’m on the mobile app so I doesn’t give me the option to write it in the specific boxes like normal. If you prefer, here is the CodePen: https://codepen.io/Nikofem/pen/RwwgGog
Here is the HTML code:
<div class="recipe-card">
<aside>
<img src="https://divascancook.com/wp-content/uploads/2015/01/no-bake-engery-bites-peanut-butter-chocolate-healthy-granola-snack-recipe-2.jpg" alt="Granola Engergy Bites" />
</aside>
<article>
<h2 id="name1"></h2>
<h4 id="ingredients1"></h4>
<ul>
<li><span class="icon icon-users"></span><span>10 - 15</span></li>
<li><span class="icon icon-clock"></span><span>15 min</span></li>
</ul>
</article>
</div>
Here is the JS code I have so far:
function Recipe(name, ingredients) {
this.name = name;
this.ingredients = [];
}
var recipe1 = new Recipe('Granola Energy Bites', ['1 cup old-fashioned oats', '1/4 tsp salt', '1/4 tsp cinnamon']);
var recipe1Name = recipe1.name;
name1.innerHTML = recipe1Name;
var recipe1Ingredients = recipe1.ingredients[0];
ingredients1.innerHTML = recipe1Ingredients;
Upvotes: 0
Views: 61
Reputation: 815
Please try and learn debugging first. Your issue is you are not doing anything with the ingredients parameter.
Your function should be:
function Recipe(name, ingredients) {
this.name = name;
this.ingredients = ingredients;
}
The code on the bottom is also incorrect, it should be:
var recipe1 = new Recipe('Granola Energy Bites', ['1 cup old-fashioned oats', '1/4 tsp salt', '1/4 tsp cinnamon']);
var recipe1Name = recipe1.name;
document.getElemendById("name1").innerHTML = recipe1Name;
var recipe1Ingredients = recipe1.ingredients;
insertToIngredients = "";
for (var i = 0; i<recipe1Ingerdients.length; i++) {
insertToIngredients = insertToIngredients + "<br>"+ recipe1Ingredients[i];
}
document.getElementById("ingredients1").innerHTML = insertToIngredients;
Upvotes: 0
Reputation: 576
In line 3 of your javascript, you are defining ingredients to be an empty array. You can fix this problem by writing
this.ingredients = ingredients
instead. You can also use a nifty tool called destructuring, if you'd like, and you could write it as
this.ingredients = [...ingredients]
Upvotes: 2