0

I wanna store multiple data when Add to Cart is clicked by the user in Local Storage Python Flask Code

{% for data in product_data %}
                    <div class="shop-item" >
                        <span class="shop-item-title" id="title-item">{{ data.title }}</span>
                        <input type="image" class="shop-item-image" id="image-item" src={{ data["img_file"] }} onclick="takethatpage();">
                        <div class="shop-item-details">
                            <span class="shop-item-price" id="price-item">{{ data["price"]}}</span>
                            <button class="btn btn-primary shop-item-button" type="button">ADD TO CART</button>
                        </div>
                    </div>
                {% endfor %} 

JS code

function addToCartClicked(event)
{
    var button = event.target
    var shopItem = button.parentElement.parentElement
    var title = shopItem.getElementsByClassName('shop-item-title')[0].innerText
    var price = shopItem.getElementsByClassName('shop-item-price')[0].innerText
    var imgSrc = shopItem.getElementsByClassName('shop-item-image')[0].src
    console.log(imgSrc)
    addItemToCart(title,price,imgSrc)
}
function addItemToCart(title,price,imgSrc)
{

}
tejas vir
  • 9
  • 1
  • 1
  • 7
  • How about create an object in javascript, then stringify it, store it as string in localStorage, and then once you read it, then parse it as json – Shashank May 24 '20 at 13:07
  • @Shashank i tried it before but it didn't stored multiple data in the Local Storage so i deleted all of that code – tejas vir May 24 '20 at 13:10
  • Did you tried this: https://stackoverflow.com/a/2010948/3523510 ? – Shashank May 24 '20 at 13:13
  • Yeah i tried this Stuff covert it into Json and then add it into Local Storage but when i clicked button of another product it keeps on overwriting it i wanted to fix it but later on i tried it using rest api but i didnt understand how to do it with rest so i think local storage would be best for this project @Shashank – tejas vir May 24 '20 at 13:27

1 Answers1

0
function addItemToCart(title,price,imgSrc) {
    let json = localStorage.getItem('card');
    if (!json) {
        card = [];
    } else {
        card = JSON.parse(json);
    }
    const item = {title.title,price:price,imgSrc:imgSrc};
    card.push(item);
    localStorage.setItem('card', JSON.stringify(card, null, 2));
}
Marc
  • 1,836
  • 1
  • 10
  • 14