Displaying certain Items from a page on another page

38 views Asked by At

I'm trying to build an amazon clone website. It has a homepage where User can add Items to their cart, this code holds the checkout page where the user can checkout the items added to the cart.

So the code gets the items added to the cart and displays it on the checkout page (generated by Javascript- cartItemHtml). There are also functions where User can update the quantity of the items or delete items.

What I want to achieve now is:

There's a button with class js-place-order-button. The items in the cart or on the webpage should be moved and displayed on a new webpage called order.html. The cart should be cleared after by setting the cartQuantity back to 0 on clicking the button.

NB: I tried creating a new cart and pushed the items in the former cart to the new one and storing the new cart using localStorage which worked. But the problem was, when I exported the new cart and imported it into my order.js it started generating this error on the order.html page

Uncaught TypeError: Cannot set properties of null (setting 'innerHTML')at checkout.js:110:55)

Does anyone have an idea why this error is being generated on the order.html page or does anyone have an idea how to display the items on the order.html page and clear the cart so the checkout page would be empty?

import { cart, cartRemoveItem, topCartQUantity, clearCart } from "../data/cart.js";
        import { formatDate } from "../data/utils.js";
        import { products } from "../data/products.js";
        
    const DAY3_DELIVERY_FEE = 999/100
    const DAY6_DELIVERY_FEE = 499/100
    const DAY12_DELIVERY_FEE = 0
    const date= new Date();
    let cartItemHtml = '';
    let checkedRadioValues = {};
    
    cart.forEach(
      (cartItem) => {
        const productId = cartItem.productId;
        
        let matchingProduct;
        products.forEach(
          (product) => {
            if (product.id === productId){
              matchingProduct = product;
            }
          }
        );
      
      cartItemHtml+=  `
      <div class="cart-item-container js-cart-item-container-${matchingProduct.id}">
      <div class="delivery-date js-delivery-date-${matchingProduct.id}">
        Delivery date: Pick a delivery date
      </div>
    
      <div class="cart-item-details-grid">
        <img class="product-image"
          src="${matchingProduct.image}">
    <div class="cart-item-details">
      <div class="product-name">
      ${matchingProduct.name}
      </div>
      <div class="product-price js-product-price" data-product-id="${matchingProduct.id}">
      $${((matchingProduct.priceCents)/100).toFixed(2)}
      </div>
      <div class="product-quantity">
        <span>
          Quantity: <span class="quantity-label js-quantity-label-${matchingProduct.id}">${cartItem.quantity}</span>
        </span>
        <span class="update-quantity-link link-primary js-update-quantity-link" data-product-id="${matchingProduct.id}">
          Update
        </span>
        <span class="js-quantity-update-${matchingProduct.id}"></span>
        <span class="delete-quantity-link link-primary js-delete-quantity-link" data-product-id="${matchingProduct.id}" data-quantity="${cartItem.quantity}">
          Delete
        </span>
      </div>
    </div>

    <div class="delivery-options">
      <div class="delivery-options-title">
        Choose a delivery option:
      </div>

      <div class="delivery-option js-delivery-option">
        <input type="radio" checked class="delivery-option-input js-delivery-option-input"
          name="delivery-option-${matchingProduct.id}" data-product-id="${matchingProduct.id}">
        <div>
          <div class="delivery-option-date js-delivery-option-date">
          ${formatDate(date, date.getDay()+12, date.getDate()+12)}
          </div>
          <div class="delivery-option-price js-delivery-option-price-${matchingProduct.id}">
            FREE Shipping
          </div>
        </div>
      </div>
      <div class="delivery-option js-delivery-option">
        <input type="radio" class="delivery-option-input js-delivery-option-input"
          name="delivery-option-${matchingProduct.id}" data-product-id="${matchingProduct.id}">
        <div>
          <div class="delivery-option-date js-delivery-option-date">
            ${formatDate(date, date.getDay()+6, date.getDate()+6)}
          </div>
          <div class="delivery-option-price js-delivery-option-price-${matchingProduct.id}">
            $${DAY6_DELIVERY_FEE} - Shipping
          </div>
        </div>
      </div>
      <div class="delivery-option js-delivery-option">
        <input type="radio" class="delivery-option-input js-delivery-option-input"
          name="delivery-option-${matchingProduct.id}" data-product-id="${matchingProduct.id}">
        <div>
          <div class="delivery-option-date js-delivery-option-date">
          ${formatDate(date, date.getDay()+3, date.getDate()+3)}
          
          </div>
          <div class="delivery-option-price js-delivery-option-price-${matchingProduct.id}">
            $${DAY3_DELIVERY_FEE} - Shipping
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

    `
  }
)
document.querySelector('.js-order-summary').innerHTML = cartItemHtml;

function updateCartQuantity(){
  let cartQuantity = 0;
  cart.forEach((item) => {
  cartQuantity += item.quantity;
});
document.querySelector('.js-checkout-header-middle-section > a').innerHTML = cartQuantity;
document.querySelector('.js-item-update').innerHTML = `Items (${cartQuantity}):`;
} 

updateCartQuantity();
document.querySelectorAll('.js-delete-quantity-link').forEach(
  (link) =>{
    link.addEventListener('click', () => {
      const productId= link.dataset.productId;
      const quantity = link.dataset.quantity;
      cartRemoveItem(productId);
      const container = document.querySelector(`.js-cart-item-container-${productId}`);
      container.remove();
      updateCartQuantity()
      
      const radioGroupName = `delivery-option-${productId}`;

      if (checkedRadioValues[radioGroupName]) {
        checkedRadioValues[radioGroupName].value = 0;
      }
      
      document.querySelector('.js-shipping-fee').innerHTML = `$${(calculateTotalSum()/100).toFixed(2)}`;
      calculatePrice()
      calculateTotalSum();

      updatePlaceOrderButton();
    })
  }
)

document.querySelectorAll('.js-update-quantity-link').forEach(
  (link) => {
    link.addEventListener('click', () => {
      let updateInput = '';
      const productId= link.dataset.productId;

      updateInput += `
        <input type="number" value="1" class="quantity-input js-quantity-input-${productId}">
        <span class="js-save-quantity-link-${productId} link-primary">Save</span>
      `
      document.querySelector(`.js-quantity-update-${productId}`).innerHTML = updateInput;
      const saveElement = document.querySelector(`.js-save-quantity-link-${productId}`);
      saveElement.addEventListener('click', () =>{
    
        // let previousQuantity = Number(document.querySelector('.js-quantity-label').innerHTML)
        let newQuantity =  document.querySelector(`.js-quantity-input-${productId}`).value;
        // previousQuantity+= Number(newQuantity);
        
        // console.log(previousQuantity);
        document.querySelector(`.js-quantity-label-${productId}`).innerHTML = topCartQUantity(productId, Number(newQuantity));
        document.querySelector(`.js-quantity-update-${productId}`).innerHTML = '';
        updateCartQuantity();
        calculatePrice()
})
  })
});
let shippingPriceTotal = 0;

const selectedDeliveryDate = {};
document.querySelectorAll('.js-delivery-option-input').forEach(
  (radio) => {
    const productId= radio.dataset.productId;
    const deliveryOptionDiv = radio.closest('.js-delivery-option');
    const dateDiv = deliveryOptionDiv.querySelector(`.js-delivery-option-date`);
    calculateTotalSum();
    if (radio.checked){
      selectedDeliveryDate[productId] = { value : dateDiv.textContent.trim()}
      document.querySelector(`.js-delivery-date-${productId}`).innerHTML = `Delivery date: ${dateDiv.textContent.trim()}`;
      document.querySelector('.js-shipping-fee').innerHTML = `$${shippingPriceTotal.toFixed(2)}`
    }
 
    radio.addEventListener('click', () => {
      const currentInputName = radio.getAttribute('name');
      const dateValue = dateDiv.textContent.trim();
      
      if (selectedDeliveryDate[productId]){
        if (selectedDeliveryDate[productId].value !== dateValue){
          selectedDeliveryDate[productId].value = dateValue;
        }
      }else {
        selectedDeliveryDate[productId] = { value : dateValue}
      }
      const priceDiv = deliveryOptionDiv.querySelector(`.js-delivery-option-price-${productId}`);
      const priceValue = priceDiv.textContent.trim();
      let extractedNumber = parseFloat(priceValue.slice(1))*100;
      
      if (isNaN(extractedNumber)){extractedNumber = 0};
      if (checkedRadioValues[currentInputName]) {
        if (checkedRadioValues[currentInputName].value !== extractedNumber) {
          checkedRadioValues[currentInputName].value = extractedNumber;
          document.querySelector('.js-shipping-fee').innerHTML = `$${(calculateTotalSum()/100).toFixed(2)}`;
          calculatePrice();
        }
      } else {
        checkedRadioValues[currentInputName] = { value: extractedNumber };
        document.querySelector('.js-shipping-fee').innerHTML = `$${(calculateTotalSum()/100).toFixed(2)}`;
        calculatePrice()
      }
      document.querySelector(`.js-delivery-date-${productId}`).innerHTML = `Delivery date: ${valueSelected(dateValue)}`;
      
    });   
  }
)
function calculateTotalSum() {
  let sum = 0;
  for (const currentInputName in checkedRadioValues) {
    sum += checkedRadioValues[currentInputName].value;
  }
  return sum;
}
function valueSelected(value){
      return value;
}
calculatePrice()
document.querySelector('.js-shipping-fee').innerHTML = `$${(calculateTotalSum()/100).toFixed(2)}`;

function calculatePrice(){
let priceTotal = 0;
document.querySelectorAll('.js-product-price').forEach(
  (price) => {
    
    const productId= price.dataset.productId;
    const quantity = document.querySelector(`.js-quantity-label-${productId}`).innerText
    
    const priceString = price.innerText;
    const extractedNumber = parseFloat(priceString.slice(1));
    
  priceTotal += (extractedNumber * 100) * quantity
  
  }
)
const shippingAndItemPrice = priceTotal + calculateTotalSum();
const tax = shippingAndItemPrice / 10
const orderTotal = shippingAndItemPrice + tax
document.querySelector('.js-total-before-tax').innerHTML = `$${(shippingAndItemPrice/100).toFixed(2)}`;
document.querySelector('.js-payment-summary-money').innerHTML = `$${(priceTotal/100).toFixed(2)}`;
document.querySelector('.js-tax').innerHTML = `$${(tax/100).toFixed(2)}`;
document.querySelector('.js-order-total').innerHTML = `$${(orderTotal/100).toFixed(2)}`
}


document.querySelector('.js-place-order-button').addEventListener('click', () => {
   
  // clearCart(); // Clear the cart in local storage
  
  cart.length = 0; // Clear the cart array
  document.querySelector('.js-shipping-fee').innerHTML = ``;
  checkedRadioValues = {};
  // Clear the cart item display
  document.querySelector('.js-order-summary').innerHTML = '';

  updateCartQuantity();
  calculatePrice();
  updatePlaceOrderButton();
  window.location.href = 'orders.html'
});

function updatePlaceOrderButton() {
  const placeOrderButton = document.querySelector('.js-place-order-button');
  if (cart.length === 0) {
    placeOrderButton.disabled = true;
  } else {
    placeOrderButton.disabled = false;
  }
}
updatePlaceOrderButton()
0

There are 0 answers