2

I have a array of objects that I included into my HTML. I have to be able to click on <a href='#' class='addToCart'>Order</a> and add the clicked object data to my console.log("...");.

What is the best way to do this?

Snippet:

"use strict";

document.addEventListener('DOMContentLoaded', loadMeals);

const meals = [
    {
        id: 1,
        title: 'Strawberry Salad with Poppy Seed Dressing',
        img: 'Strawberry-Salad-with-Poppy-Seed-Dressing.jpg',
        book: 1,
        calories: 298,
        servings: 3,
        type: 'lunch',
        price: 15,
        cook: 'Jenny Jefferson',
        quantity: 10,
    },
    {
        id: 2,
        title: 'Cashew Turkey Salad Sandwiches',
        img: 'turkey-sandwich.jpg',
        book: 2,
        calories: 198,
        servings: 2,
        type: 'lunch',
        price: 9,
        cook: 'Jenny Jefferson',
        quantity: 10
    }
];


function loadMeals() {
    let i = 0;
    let id = 1;
    let fillMealList = document.querySelector("#fillMealList");
    for (let i = 0; i < meals.length; i++) {
        let item = meals.find(item => item.id === id);
        fillMealList.innerHTML +=
            "<article>"+
            "<h3>" + item.title + "</h3>"+
            "<figure>"+
            "<img src='images/" + item.img + "'" +">" +
            "<figcaption>"+
            "Meal by: " +"<span>" + item.cook + "</span>" +
            "</figcaption>" +
            "</figure>"+
            "<div class='info'>"+
            "<p>€ <span>" + item.price + "</span>" + "/pp" + "</p>" +
            "<a href='#' class='addToCart'>Order</a>"+
            "</div>"+
            "</article>";
        id++;
    }
}
<div id="mealList">
            <div class="flexcontainer" id="fillMealList"></div>
            </div>

2
  • Add a click handler to the a? Commented Dec 11, 2018 at 8:01
  • 1
    Please post your HTML code as well or make a working demo/fiddle. Commented Dec 11, 2018 at 8:02

2 Answers 2

1

Change your hyperlink HTML as below:

"<a href='javascript:logMeal(" + item.id + ")' class='addToCart'>Order</a>"+

And add a new function called logMeal as below:

function logMeal(id) {
    console.log(meals.find(item => item.id === id));
}
Sign up to request clarification or add additional context in comments.

1 Comment

Okay, I did this but i'ts showing the same meal ( with id== 1) even if i click the one with id == 2
1

you can just add an onclick Event to your <a> tag : <a class="addToCart" onclick="addToCart(item)">order</a>

then define the function addToCart()

function addToCart(item) {              
console.log(item)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.