Add new Item with the same form to an existing Session-Storage

1.3k Views Asked by At

I have a form that is called via modal anytime the user it's the button. It's used here: http://fromlandmark.com/projects/VacuumStore/product.php

Everytime I called the form via the "Remplir..." Button, I add to the sessionStorage the Item.

The problem is, that, later I want to add another item with the same form and the sessionStorage is being updated with new values. I want to add a new Item to be able to display the shopping cart list later.

This is the piece of code that store the values of the inputs and add to the storage:

$('.submit-message').click(function (e) {
  e.preventDefault();
  //message
  var productID = $('.modal').attr('product-name');
  var productImg = $('.product-image').attr('src');
  var message = $('#message').val();

  // from inputs
  var fromName = $('#from-name-input').val();
  var fromLastName = $('#from-last-name-input').val();
  var fromAddress = $('#from-address-input').val();
  var fromCountry = $('#from-country-input').val();
  var fromCity = $('#from-city-input').val();
  var fromPostalCode = $('#from-postalcode-input').val();
  var fromPhone = $('#from-phone-input').val();

  // to inputs
  var toName = $('#to-name-input').val();
  var toLastName = $('#to-last-name-input').val();
  var toAddress = $('#to-address-input').val();
  var toCountry = $('#to-country-input').val();
  var toCity = $('#to-city-input').val();
  var toPostalCode = $('#to-postalcode-input').val();
  var toPhone = $('#to-phone-input').val();

  let productInfo = {
    FromName: fromName,
    FromLastName : fromLastName, 
    FromAdress: fromAddress,
    FromCountry: fromCountry,
    FromCity: fromCity,
    FromPostCode: fromPostalCode,
    FromPhone : fromPhone,
    FromName: toName,
    ToLastName : toLastName, 
    ToAdress: toAddress,
    ToCountry: toCountry,
    ToCity: toCity,
    ToPostCode: toPostalCode,
    ToPhone : toPhone,

    Message: message,
    Product: productImg,
    ProductID : productID

  };

  sessionStorage.setItem('productList', JSON.stringify(productInfo));
  var storedProductList = JSON.parse(sessionStorage.getItem('productList')); 
  })
1

There are 1 best solutions below

0
On

Store product list in session storage as a JSON array.

Initial de-serialized value from of product list is null and should default to an array.

var storedProductList = JSON.parse(
  sessionStorage.getItem('productList')) || [];

Append productInfo to this array.

storedProductList.push(productInfo);

Finally, store this to session storage.

sessionStorage.setItem('productList', 
JSON.stringify(storedProductList));