How do I select data from element with onClick listener

I'm currently working on a web application that has to function as some sort of webshop later on. I'm now working on an addToCart function, that has to pick certain data from the clicked element (the name and the price of the product, and add 1 to pcs and save everything to a session), and paste these 2 values into a template I've made and place the template with the values to the shopCart.

This is the current javascript code I've made for loading in all the products, and my attempt on showing some of the values of the item clicked at that moment:

$(function(){
    $.getJSON("assets/products/sample_products.json", function(response) {
        $.each(response.data, function (i, el) {
            let card = $($('#productCard-template').html());
            card.find('#cardName').html( el.name);
            card.find('#cardPrice').html( '€' + el.price );
            card.find('.productItem').attr('data-price', el.price)
                .attr('data-article-number', el.article_number)
                .attr('data-id', el.id)
                .attr('data-name', el.name)
                .attr('data-stock', el.stock)
                .attr('data-categories', el.categories);
            $('#touchViewProducts').append(card);
        });
    });
});

//onclick function adds data of product to the designated template
function addToCart(){
    var value = document.getElementById("productCard").value;
    var getDataVal = document.getElementById('productCard-template').getAttribute('data-name', 'data-price');
    var total = 0;
    console.log(this.data-name)

}

This is the html code of the templates:

<script type="text/template" id="productCard-template">
    <div class="col-3 productCard" id="productCard" onclick="addToCart()">
        <a href="#" class="productItem">
            <div class="card">
                <img src="assets/images/Firecracker.jpg" alt="Avatar" style="width: 100%; height: 8vh;">
                <div class="container">
                    <div class="row" style="height: 6vh; max-width: 20ch;">
                        <p id="cardName"> </p>
                    </div>

                    <div class="row" style="height: 50%">
                      <b><p id="cardPrice"></p></b>
                    </div>
                </div>
            </div>
        </a>
    </div>
</script>

<script type="text/template" id="shopcartRow-template">
    <div class="row">
        <div class="col-5" id="valueName"> </div>
        <div class="col-1" id="valueQty"> </div>
        <div class="col-2" id="valuePrice"> </div>
        <div class="col-3" id="valueTotal"> </div>
    </div>
</script>

Here's an image of what the web app looks like, when clicked on the card that contains "Oscar and price 89", I would like the function to add it to the cart with product "oscar", pcs. 1 (pcs += 1), price "89" and total would be "89" too then

1 answer

  • answered 2020-09-28 11:48 Cedric Cholley

    Since every items in your list has a serie of data-* attribute (with the id, name, …) I think the easiest would be to create an item object (based on those data-* attributes) and to add it to a Cart class.

    The Cart class would have an Items property where content of the chart will be stored. Items should be a Map(), this would help managing duplicate, remove item and so on.

    Here is a code example of what Chart could be, how to add item(s) and how to calculate the price of the cart.

    
    class Cart {
      constructor() {
        this.items = new Map();
      }
      
      get price() {
        return [...this.items.values()].reduce((price, item) => price += item.price, 0);
      }
    }
    
    
    const cart = new Cart();
    
    // this would be inside addToCart() funtion. Values would be retrived thanks to data-*
    cart.items.set(1, {
      price: 100,
      name: 'shoes'
    });
    cart.items.set(2, {
      price: 30,
      name: 'socks'
    });
    
    
    console.log(cart.price)