skip to Main Content

So I built that it add product to cart and to specific div in checkout page,now I need to paste total from checkout page to index page which is in this case payment page.I tried something but it still do not display total.
heres product page

<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>
                  <h3>Select Licence</h3>
                  <select id="select" class="licence">
                    <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 = {
                        "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>
                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 productImage = document.getElementById('product-image');
      const ImageSrc = productImage.src;
      const audioElement = document.getElementById('audio-clip');
      const audioSrc = audioElement.src;

      const cartItem = {
        title: productTitle,
        price: productPrice,
        license: selectedLicense,
        image: ImageSrc,
        audio: audioSrc
      };

      let selectedItems = JSON.parse(localStorage.getItem('selectedItems')) || [];

      // Check if the item already exists in the cart
      let existingItemIndex = selectedItems.findIndex(item => item.title === productTitle && item.license === selectedLicense);

      if (existingItemIndex > -1) {
        // If the item already exists, update the license
        selectedItems[existingItemIndex].license = selectedLicense;
      } else {
        // If the item doesn't exist, add it to the cart
        selectedItems.push(cartItem);
      }

      console.log(selectedItems);

      localStorage.setItem('selectedItems', JSON.stringify(selectedItems));
    });
  }
</script>

and heres checkout page


  <div class="total">
    <form action="index.html" class="total">
    <h3 style="text-align:center; display: none;">Subtotal: <br><span id="subtotal"></span></h3>
    <h3 style="text-align:center;">Total: <br><span id="total">$0</span></h3>
    <a href="index.html"><button type="submit" class="buy-btn" style="background-color: rgb(29, 4, 216);">Continue to purchase</button></a>
    <a href="index.html" onclick="alert('You will be redirected to the home page')"><button style="background-color: rgb(216, 4, 4);">Cancel</button></a>
  </div>
</form>
  <!--It does clear but wonder , make that you cant click on button if that function is done-->
</body>
<script>
  const cartItemsDiv = document.querySelector(".cart-items");
  const storedCartItem = localStorage.getItem("selectedItems");  
  let subtotal = 0;

  const continueButton = document.getElementById("buy-btn");
  const clearButton = document.getElementById("clear-button");

  function clearCartItems() {
  // Clear the HTML content of the cart-items div
  const cartItemsDiv = document.querySelector(".cart-items");
  cartItemsDiv.innerHTML = "";

  // Set the subtotal and total to $0
  const subtotalSpan = document.getElementById("subtotal");
  const totalSpan = document.getElementById("total");
  subtotalSpan.innerHTML = "";
  totalSpan.innerHTML = "$0";

  // Remove the selected items from localStorage
  localStorage.removeItem("selectedItems");

  alert("Added items will be cleared.");
  // Change the URL to the index page and prevent going to the checkout page
  window.location.href = "sproduct6.html";
  history.replaceState(null, "", window.location.href);

  // Update the UI
  document.getElementById("added-products").innerHTML = "You have no items in your cart!";
  document.getElementById("buy-btn").style.display = "none";
  document.getElementById("clear-button").style.display = "none";

   if (cartItemCount == 0) {
    setTimeout(function() {
      alert("You have no items in your cart. Let's get back to product page.");
      window.location.href = ('sproduct6.html');
    }, 50); // 3 second delay 
    document.getElementById("added-products").innerHTML = "You have no items in your cart!";
    continueButton.style.display = "none";
    clearButton.style.display = "none";
    // Save the visibility state of the buttons
    localStorage.setItem("buttonsVisible", "false");
  } else {
    document.getElementById("added-products").innerHTML = "YOU ADDED THIS PRODUCTS";
  } 
}

if (storedCartItem) {
  const cartItem = JSON.parse(storedCartItem); // Parse the storedCartItem string into an array

  for (let i = 0; i < cartItem.length; i++) {
    const cartItemElement = document.createElement("div");  

    
    cartItemElement.innerHTML = `
        <hr />
        <h3>${cartItem[i].title}</h3>  
        <p>Price: ${cartItem[i].price}</p>
        <p>License: ${cartItem[i].license}</p>
        <img src="${cartItem[i].image}" width='30%'/><br>
        <audio controls style="width:50%;">
          <source src="${cartItem[i].audio}" type="audio/mp3"> 
        </audio>
        `;
    // ADD DELETE OPTION 

    cartItemsDiv.appendChild(cartItemElement);

    const price = Number(cartItem[i].price.replace("$", "")); // Parse price as a number and remove dollar sign
    subtotal += price;
    // MAKE REPLACE TITLE TO YOU HAVE NO ITEMS IN YOUR CART
  }

  const subtotalElement = document.querySelector("#subtotal");
  subtotalElement.textContent = `$${subtotal.toFixed(2)}`;

  const totalElement = document.querySelector("#total");
  const total = subtotal;
  totalElement.textContent = `$${total.toFixed(2)}`;
  const totalPriceInput = document.querySelector("#total_price");
  totalPriceInput.value = total.toFixed(2);
}

function passtotal(){
  var total = document.getElementById('total').value;
  var subtotal = document.getElementById('subtotal').value;
  localStorage.setItem("value", total);
  return false;
}
</script>

and heres index page where total should display in total span


  <body>
    <div class="sr-root">
      <div id="total"></div>
      <div class="sr-main">
        <h1>Pay with a bunch of payment option</h1>

        <form id="payment-form" method="POST">
          <input type="text" name="email" id="email" placeholder="E-Mail" required>
          <input type="text" name="name" id="name" placeholder="Full Name" required>
    
          <div id="payment-element"></div>
    
          <button>Pay</button><!--Make functional-->
          <!--Make total price hidden and that total of this is same as in checkout and that its connected to ruby-->
          <div id="error-messages"></div>
        </form>        
      </div>
    </div>
    <script>
      var getValue = localStorage.getItem("value");
      var value = JSON.parse(getValue);
      document.getElementById("total").innerHTML=localStorage.getItem("value");
    </script>

2

Answers


  1. Chosen as BEST ANSWER

    I changed that to total id which is correct but it still does not display total of checkout page in index page : heres current code of checkout page

      <div class="total">
        <form action="index.html" class="total">
        <h3 style="text-align:center; display: none;">Subtotal: <br><span id="subtotal"></span></h3>
        <h3 style="text-align:center;">Total: <br><span id="total">$0</span></h3>
        <a href="index.html"><button type="submit" class="buy-btn" style="background-color: rgb(29, 4, 216);">Continue to purchase</button></a>
        <a href="index.html" onclick="alert('You will be redirected to the home page')"><button style="background-color: rgb(216, 4, 4);">Cancel</button></a>
      </div>
    </form>
      <!--It does clear but wonder , make that you cant click on button if that function is done-->
    </body>
    <script>
      const cartItemsDiv = document.querySelector(".cart-items");
      const storedCartItem = localStorage.getItem("selectedItems");  
      let subtotal = 0;
    
      const continueButton = document.getElementById("buy-btn");
      const clearButton = document.getElementById("clear-button");
    
      function clearCartItems() {
      // Clear the HTML content of the cart-items div
      const cartItemsDiv = document.querySelector(".cart-items");
      cartItemsDiv.innerHTML = "";
    
      // Set the subtotal and total to $0
      const subtotalSpan = document.getElementById("subtotal");
      const totalSpan = document.getElementById("total");
      subtotalSpan.innerHTML = "";
      totalSpan.innerHTML = "$0";
    
      // Remove the selected items from localStorage
      localStorage.removeItem("selectedItems");
    
      alert("Added items will be cleared.");
      // Change the URL to the index page and prevent going to the checkout page
      window.location.href = "sproduct6.html";
      history.replaceState(null, "", window.location.href);
    
      // Update the UI
      document.getElementById("added-products").innerHTML = "You have no items in your cart!";
      document.getElementById("buy-btn").style.display = "none";
      document.getElementById("clear-button").style.display = "none";
    
       if (cartItemCount == 0) {
        setTimeout(function() {
          alert("You have no items in your cart. Let's get back to product page.");
          window.location.href = ('sproduct6.html');
        }, 50); // 3 second delay 
        document.getElementById("added-products").innerHTML = "You have no items in your cart!";
        continueButton.style.display = "none";
        clearButton.style.display = "none";
        // Save the visibility state of the buttons
        localStorage.setItem("buttonsVisible", "false");
      } else {
        document.getElementById("added-products").innerHTML = "YOU ADDED THIS PRODUCTS";
      } 
    }
    
    if (storedCartItem) {
      const cartItem = JSON.parse(storedCartItem); // Parse the storedCartItem string into an array
    
      for (let i = 0; i < cartItem.length; i++) {
        const cartItemElement = document.createElement("div");  
    
        
        cartItemElement.innerHTML = `
            <hr />
            <h3>${cartItem[i].title}</h3>  
            <p>Price: ${cartItem[i].price}</p>
            <p>License: ${cartItem[i].license}</p>
            <img src="${cartItem[i].image}" width='30%'/><br>
            <audio controls style="width:50%;">
              <source src="${cartItem[i].audio}" type="audio/mp3"> 
            </audio>
            `;
        // ADD DELETE OPTION 
    
        cartItemsDiv.appendChild(cartItemElement);
    
        const price = Number(cartItem[i].price.replace("$", "")); // Parse price as a number and remove dollar sign
        subtotal += price;
        // MAKE REPLACE TITLE TO YOU HAVE NO ITEMS IN YOUR CART
      }
    
      const subtotalElement = document.querySelector("#subtotal");
      subtotalElement.textContent = `$${subtotal.toFixed(2)}`;
    
      const totalElement = document.querySelector("#total");
      const total = subtotal;
      totalElement.textContent = `$${total.toFixed(2)}`;
      const totalPriceInput = document.querySelector("#total");
      totalPriceInput.value = total.toFixed(2);
    }
    
    function passtotal(){
      var total = document.getElementById('total').value;
      var subtotal = document.getElementById('subtotal').value;
      localStorage.setItem("value", total);
      return false;
    }
    </script>

    and this is my index page code :

    class="sr-root">
          <span id="total"></span>
          <div class="sr-main">
            <h1>Pay with a bunch of payment option</h1>
    
            <form id="payment-form" method="POST">
              <input type="text" name="email" id="email" placeholder="E-Mail" required>
              <input type="text" name="name" id="name" placeholder="Full Name" required>
        
              <div id="payment-element"></div>
        
              <button>Pay</button><!--Make functional-->
              <!--Make total price hidden and that total of this is same as in checkout and that its connected to ruby-->
              <div id="error-messages"></div>
            </form>        
          </div>
        </div>
        <script>
          var getValue = localStorage.getItem("value");
          var value = JSON.parse(getValue);
          document.getElementById("total").innerHTML=localStorage.getItem("value");
        </script>


  2. You error is happening where you are assigning to the value property of an element. You are only doing that in one place in the code you posted:

    const totalPriceInput = document.querySelector("#total_price");
    totalPriceInput.value = total.toFixed(2);
    

    That error means when your code runs, totalPriceInput is undefined and it can’t find the value property on undefined

    So that mean that your querySelector is not getting anything back. My guess is that it cannot find an element in your HTML with the ID total_price – you should double check this and make sure that this ID is correct.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search