Save the chosen items in localStorage for future rendering

I've been developing a shopping cart application that utilizes a JSON file to store menu items. Using JavaScript, I have successfully rendered the menu items in HTML by creating a forEach loop and using document.createElement() along with appendChild(). When a user clicks on an "Add to Cart" button, I capture the details of the selected menu item, retrieve its price from the JSON file, and then invoke a helper function to calculate the final price.

QUERY:
My current challenge is storing the user's selected items in localStorage and then utilizing this data to display Cart Details. How can I achieve this? Could you provide a relevant code snippet based on my existing code? Additionally, I need guidance on how to store the image details of the menu item in localStorage.

SAMPLE CODE:
store.js

//Function triggered when "Add to Cart" button is clicked
function addToCartClicked(event) {
  //Fetch all details of the selected item
  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 sizePrices = document.getElementsByName("sizes"); 
  var size_price;
  for (var i = 0; i < sizePrices.length; i++) {
    if (sizePrices[i].checked) {
      size_price = sizePrices[i].value;
      break;
    }
  }
  var imageSrc = shopItem.getElementsByClassName("shop-item-image")[0].src;
  price = parseFloat(price.replace("Rs.", "")) + parseFloat(size_price);
  console.log(price);
  addItemToCart(title, price, imageSrc, size_price);
  updateCartTotal();
}

//Utility function for addToCartClicked
function addItemToCart(title, price, imageSrc, size_price) {
  var cartRow = document.createElement("div");
  cartRow.classList.add("cart-row");
  var cartItems = document.getElementsByClassName("cart-items")[0];
  var cartItemNames = cartItems.getElementsByClassName("cart-item-title");
  
  var cartRowContents = `
        <div class="cart-item cart-column">
            <img class="cart-item-image" src="${imageSrc}" width="100" height="100">
            <span class="cart-item-title">${title}</span>
            <span class="cart-item-size">"Rs.${size_price}"</span>
        </div>
        <span class="cart-price cart-column">${price}</span>
        <div class="cart-quantity cart-column">
            <input class="cart-quantity-input" type="number" value="1">
            <button class="btn btn-danger" type="button">REMOVE</button>
        </div>`;
  cartRow.innerHTML = cartRowContents;
  cartItems.append(cartRow);
  cartRow.getElementsByClassName("btn-danger")[0].addEventListener("click", removeCartItem);
  cartRow.getElementsByClassName("cart-quantity-input")[0].addEventListener("change", quantityChanged);
}

data.json

{
  "pizza": [
    {
      "id": 1,
      "name": "Tandoori Pizza",
      "image": "Images/pizza.png",
      "price": "Rs.200",
      "sizes": { "Small": 100, "Medium": 200, "Large": 300 }
    },
    {
      "id": 2,
      "name": "Veggie Supreme",
      "image": "Images/pizza.png",
      "price": "Rs.250",
      "sizes": { "Small": 100, "Medium": 200, "Large": 300 }
    }
  ]
}

I'm looking for guidance on implementing localStorage for storing selected items and rendering them under Cart Items. Any insights provided should be purely JavaScript-based as that is my preferred approach.

Answer №1

localStorage is a storage object used for saving data across browser sessions within the Document's origin.

The method setItem() allows you to store data in the browser.

To retrieve the stored data from the browser, you can utilize getItem().

var cartObj = {
  'id': 1,
  'name': 'Tandoori Pizza',
  'image': 'Images/pizza.png',
  'price': '200'
};

// Storing the object in localStorage
localStorage.setItem('cartMenu', JSON.stringify(cartObj));

// Retrieving the object from localStorage
var menuItemInCart = localStorage.getItem('cartMenu');

console.log('menuItemInCart: ', JSON.parse(menuItemInCart));

For a demonstration of this functionality, check out this JSFiddle example.

Answer №2

To start, generate a document with the following structure: settings.js

export default {
// insert json data here
}

Next, follow these steps:

import jsonData from './settings.js'

var parsedData = JSON.parse(jsonData);
window.localStorage.setItem('cart', parsedData); // saves the information to localStorage

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporating JavaScript Variables into MySQL Database with AJAX: A Step-By-Step

Looking to implement the solution provided in this query about adding records into a database using php/ajax/mysql: Best way to add records into DB using php/ajax/mysql? This is my current code: JavaScript function FromFlash(m1, m2, m3, m4){ var po ...

PHP code cannot be executed due to a problem with Angular routing

I stumbled upon this previous discussion during my search for assistance with a particular problem, but unfortunately there were no responses that could provide a solution. The issue I am facing involves submitting a form and expecting to receive a php va ...

Steps for combining two collections into a single output in MongoDB with Node.js

My MongoDB collections consist of data that I need to merge using the $lookup operation. However, the result I get contains a nested array structure that is not ideal. I am looking for a solution to format the result as shown below: First collection locati ...

Navigating through Node and Express on Azure App Service

I'm facing an issue that I am not sure if it is related to Node or Azure App Service, so here's the situation: In my Node/Express app, I have defined two routes: router.get("/users", checkAuthHeader, userController.getUsers); router.po ...

Retrieve the JSON array embedded within the JSON string

Can someone help me extract the JSON array from a JSON string? I've been struggling to make it work. Here is the code snippet for reference: // I need assistance with this var all_barcodes = '{"VAM12345":{"colour":"red","size":"32"},"VAM456789" ...

Waiting in iOS UI Automation for the web view to be prepared and displayed

In my quest to develop an iOS UI Automation javascript with Instruments for automating the process of taking a screenshot in my iOS app, I have turned to the handy tool known as Snapshot. A crucial part of my app involves a webview, and I am keen on captu ...

Vue's span function is yielding the promise object

In my Vue component, I am using the function getOrderCount to fetch the number of orders from a specific URL and display it in one of the table columns. <div v-html="getOrderCount(user.orders_url)"></div> async getOrderCount(link) { ...

Modifying radio inputs to update when a state variable is altered in react.js

In my HTML, I have a div that includes 4 radio inputs, and another div with an onClick event that increments a counter. Every time I click on the div, I want the radio inputs to reload so that no input is selected. Below is the code snippet: 'use clie ...

Video background mute feature malfunctioning

I've searched through numerous resources and reviewed various solutions for this issue, yet I still haven't been able to figure it out. Could someone please guide me on how to mute my youtube embedded video? P.s. I am a beginner when it comes to ...

Ways to invoke a prop function from the setup method in Vue 3

I encountered the following code: HTML: <p @click="changeForm">Iniciar sesion</p> JS export default { name: "Register", props: { changeForm: Function, }, setup() { //How do I invoke the props change ...

AngularJS is capable of dynamically altering the URL based on the specific HTTP method being used, such as

I have implemented Angular factories to connect ajax requests with my web api. Below is an example of how the factory is structured. app.factory('QuestionContainer', ['$resource', function ($resource) { return $resource('http://lo ...

"Utilizing JQuery to enhance task management by implementing a delete function

I need help figuring out how to create a function that can delete tasks from my todo list. Currently, each task has its own remove button, but I want to implement a single remove button at the bottom that removes checked or crossed out tasks. Any suggestio ...

Rails: Ensure that JSON form fields remain populated in case the form encounters a validation error

I am using a rails simple form to create a product with three fields inside in order to associate it with appropriate categories: <div class="form-group"> <%= f.input :child_category_id, :collection => @categories.order(:name), :l ...

Here is a way to attach a function to dynamically generated HTML that is returned in an AJAX request

As I was working on a new function development project, I encountered a situation where I had to add a function to dynamically generated HTML through an ajax call. The following is a snippet of the code: $.ajax( 'success': function(data){ ...

Mongoose (mongodb) node returning null JSON object when using Model.find()

Below is the code snippet in question: app.get('/all', function(req,res) { Party.find({},[],function(p) { console.log(p); }); res.redirect('/'); }); The goal was to retrieve all collections from the database, but it returns ...

How can you display rows in a mysqli result without explicitly stating the column names?

Is there a way to output all rows from a query result in JSON format without explicitly stating each column name? In other words, is it possible to avoid writing 'location_id' => $row['location_id'] for every column, like shown below ...

Tips for making my JavaScript form open a new window after submitting

Currently, the link opens in the same window when submitted. I would like it to open in a new window instead. This is the script in the head section: <script type="text/javascript"> function getURL(val){ base = 'http://www.domain.com/'; ...

Angular: Struggling with Parent Component not recognizing changes in Child Component

Currently, I am facing an issue with my shopping cart functionality. When the website first loads and a user does not have a saved shopping cart, they need to click "add to cart" before one is created. The problem lies in the fact that my app.component doe ...

What could possibly be causing my char* to inexplicably change its value?

Specifics: I am utilizing a project on GitHub to transform a Json into an object. https://github.com/ereilin/qt-json The Json looks like this: { "bin": "/home/pablo/milaoserver/compile/Devices01.olk", "temp":"/home/pablo/milaoserver/temporal/", ...

Instructions for creating a histogram using predetermined bin values

After searching, I noticed that most tutorials on creating histograms with matplotlib focus on plotting histograms for unbinned data using the hist function. How can I go about drawing a histogram from pre-binned data? To provide more context, here is the ...