skip to Main Content

I made a function that displays product added to cart in a specific div on another page, but when testing it out a problem occurs. For example:

  • adding product with e.g MP3 licence and $20 price
  • product with un-tagged Wav licence and $27 price
  • clicking continue to purchase
  • proceeds to checkout.html (as it should)
  • but the div displays only the last product added to cart instead of all products.

This is my code: here is product page where is function to add to cart


      <header>
        <!--Nav-->
        <div class="nav container">
          <a href="">Deni Beatz</a>
          <!--Cart Icon-->
          <i class="bx bx-shopping-bag" id="cart-icon"></i>
          <div class="notification" id="cart-notification">0</div>
          <!--Cart-->
          <div class="cart">
            <h2 class="cart-title">Your Cart</h2>
            <!--Content-->
            <div class="cart-content">
              <div class="cart-content">
                
              </div>
            </div>
            <!--Total-->
            <div class="total">
              <div class="total-title">Total</div>
              <div class="total-price" id="total-price total">$0</div>
            </div>
            <!--Buy Button-->
            <form action="checkout.html">
            <button type="button" class="btn-buy" onclick="window.location.href = 'checkout.html';">Continue to purchase</button>
            </form>
            <!--Cart Close-->
            <i class="bx bx-x" id="close-cart"></i>
            <!-- Continue to purchase button moved here -->
          </div>
        </div>
      </header>

          <section id="prodetails" class="section-p1">
            <div class="productcontainer" id="enjoy">
                <div class="single-pro-image">
                  <img src="../data/high.png"  width="100%" id="product-image" class="product-img">
                </div>
            
                <div class="single-pro-details" action="C:sstarter-rubyclientcheckout.html">
                  <h4 class="product-title" id="title">Enjoy</h4>
                  <h2 id="price" class="price">$20</h2>
                  <select id="select" class="licence">
                    <option>Select Licence</option>
                    <option>MP3</option>
                    <option>Tagged Wav</option>
                    <option>Un-Tagged Wav</option>
                    <option>Stems</option>
                    <option>Exlusive</option>
                  </select>
    
                    <script>
                      let select = document.getElementById('select');
                      let price = document.getElementById('price');
    
                      // Prices
                      let prices = {
                        "Select Licence": '$20',
                        "MP3": '$20',
                        "Tagged Wav": '$27',
                        "Un-Tagged Wav": '$30',
                        "Stems": '$120',
                        "Exlusive": '$300'
                      }
    
                      // When the value of select changes, this event listener fires and changes the text content of price to the coresponding value from the prices object
                      select.addEventListener('change', () => {
                        price.textContent = prices[select.value];
                      });
                    </script>
                    <button class="add-cart">Add To Cart <i class='bx bx-cart-add add-cart'></i></button>
                    <h4>Product Details</h4>
                    <span>Lil Tjay x Trap Type Beat - "Enjoy" in key D# Minor and 160 BPM,It has vibe of Lil Tjay , Pop Smoke and more , Prices are great for this type of beat;Tagged Mastered MP3 for $25,$27 for Tagged Unmastered Wav,$30 for Untagged unmastered Wav,$70 for Stems and $120 for Exlusive</span>
                </div>
                <div id="audio">
                    <audio controls style="width:100%;" id="audio-clip">
                        <source src="Audio/Enjoy 160 x D sharp minor.mp3" type="audio/mp3">
                    </audio>
                </div>
              </section> 

              <script>
                // ADD IMAGE AND AUDIO AND ADD + TO OPEN AND CLOSE BOX! GREAT JOB-FOR WORKING WITH HEADACHE
                const addToCartButton = document.querySelector('.add-cart');
if (addToCartButton) {
  addToCartButton.addEventListener('click', () => {
    const productTitle = document.querySelector('#title').textContent;
    const productPrice = document.querySelector('#price').textContent;
    const selectedLicense = document.querySelector('#select').value;
    
    const cartItem = {
      title: productTitle,
      price: productPrice,
      license: selectedLicense
    };
    
    localStorage.setItem('cartItem', JSON.stringify(cartItem));
  });
}

              </script>              

and heres checkout page that display just last item added to cart


  <h2 style="text-align:center;">Checkout</h2>
<div id="cart-items">
  <p style="text-align:center;">YOU ADDED THIS PRODUCTS</p>
  <hr />
  <div class="product-container">
    <button class="toggle-button"><span id="t-name"></span> <span id="t-price"></span> +</button>
    <div class="cart-items"></div>
  </div>
</div>

<div class="total">
  <h3 style="text-align:center;">Tax: <br><span id="tax"></span></h3>
  <h3 style="text-align:center;">Subtotal: <br><span id="subtotal"></span></h3>
  <h3 style="text-align:center;">Total: <br><span id="total"></span></h3>
  <a href="http://localhost:4242"><button style="display:block;">Continue to payment</button></a>
</div>

<script>
  const cartItemsDiv = document.querySelector('.cart-items');
  const storedCartItem = localStorage.getItem('cartItem');
  const taxRate = 0.10; // 10% tax rate

  if (storedCartItem) {
    const cartItem = JSON.parse(storedCartItem);
    const cartItemElement = document.createElement('div');

    cartItemElement.innerHTML = `
      <h3>${cartItem.title}</h3>
      <p>Price: ${cartItem.price}</p>
      <p>License: ${cartItem.license}</p>
    `;
    cartItemsDiv.appendChild(cartItemElement);

    // Parse price as a number and remove dollar sign
    const price = Number(cartItem.price.replace('$', ''));

    const subtotal = document.querySelector('#subtotal');
    subtotal.textContent = `$${price}`;

    const tax = document.querySelector('#tax');
    tax.textContent = `$${(price * taxRate).toFixed(2)}`;

    const total = document.querySelector('#total');
    total.textContent = `$${(price + (price * taxRate)).toFixed(2)}`;
  }
</script>

3

Answers


  1.     <script>
                    // ADD IMAGE AND AUDIO AND ADD + TO OPEN AND CLOSE BOX! GREAT JOB-FOR WORKING WITH HEADACHE
                    const addToCartButton = document.querySelector('.add-cart');
    if (addToCartButton) {
      addToCartButton.addEventListener('click', () => {
        const productTitle = document.querySelector('#title').textContent;
        const productPrice = document.querySelector('#price').textContent;
        const selectedLicense = document.querySelector('#select').value;
        
        const cartItem = {
          title: productTitle,
          price: productPrice,
          license: selectedLicense
        };
        
        localStorage.setItem('cartItem', JSON.stringify(cartItem));
      });
    }
    
                  </script>   
    

    here your add to cart function replaces already existing item that is your cart item in the local storage with the new item, instead of this you can push the items into an array and do the same, that will solve your problem. You can display the items in the chekout page by looping through this array.

    Hope this helps.

    Login or Signup to reply.
  2. the localStorage is overwritten everytime you click the button. That is why you will always have only one element in it, the last product. A different approach would be to store an array to your localstorage :

    • first get and parse the localstorage
    • push your new element to localstorage
    • then setItem

    example to get your localstorage:
    let store = JSON.parse(localStorage.getItem('cartItem')) || [];

    Login or Signup to reply.
  3. You should create an array and push each item. Change the product page like this;

    <script>
    // ADD IMAGE AND AUDIO AND ADD + TO OPEN AND CLOSE BOX! GREAT JOB-FOR WORKING WITH HEADACHE
    var selectedItems = [];
    const addToCartButton = document.querySelector('.add-cart');
    if (addToCartButton) {
        addToCartButton.addEventListener('click', () => {
            const productTitle = document.querySelector('#title').textContent;
            const productPrice = document.querySelector('#price').textContent;
            const selectedLicense = document.querySelector('#select').value;
            
            const cartItem = {
                title: productTitle,
                price: productPrice,
                license: selectedLicense
            };
    
            selectedItems.push(cartItem);
    
            console.log(selectedItems);
            
            localStorage.setItem('selectedItems', JSON.stringify(selectedItems));
        });
    }
    
    </script>   
    

    And change your checkout page to display them with for loop;

    <script>
          const cartItemsDiv = document.querySelector(".cart-items");
          const storedCartItem = localStorage.getItem("selectedItems");
          const taxRate = 0.1; // 10% tax rate
    
          if (storedCartItem) {
            const cartItem = JSON.parse(storedCartItem);
    
            for (let i = 0; i < storedCartItem.length; i++) {
              const cartItemElement = document.createElement("div");
    
              cartItemElement.innerHTML = `
              <h3>${cartItem[i].title}</h3>
              <p>Price: ${cartItem[i].price}</p>
              <p>License: ${cartItem[i].license}</p>
              `;
              cartItemsDiv.appendChild(cartItemElement);
              
            }
            
    
          
    
            // Parse price as a number and remove dollar sign
            const price = Number(cartItem.price.replace("$", ""));
    
            const subtotal = document.querySelector("#subtotal");
            subtotal.textContent = `$${price}`;
    
            const tax = document.querySelector("#tax");
            tax.textContent = `$${(price * taxRate).toFixed(2)}`;
    
            const total = document.querySelector("#total");
            total.textContent = `$${(price + price * taxRate).toFixed(2)}`;
          }
        </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search