Gcobani Mkontwana

Gcobani Mkontwana

  • 562
  • 1.8k
  • 389.2k

How to add product to cart and increment the total value?

Sep 27 2023 1:46 PM

Hi Team

I need some help with my below logic, basically i want to do 2 things. Add to cart an item and must display it to the cart badge, then when total product is 145 it must reduce when i click - button and vice versa when i click + to increment it. Currently now i unable to get this right, need some guidance. 

 

<div class="container-fluid py-5">
  <div class="row px-xl-5">
    <div class="col-lg-5 pb-5">
      <div id="product-carousel" class="carousel slide" data-ride="carousel">
        <div class="carousel-inner border">
          <div class="carousel-item active">
            <img class="w-100 h-100" src="img/product-1.jpg" alt="Image">
          </div>
          <div class="carousel-item">
            <img class="w-100 h-100" src="img/product-2.jpg" alt="Image">
          </div>
          <div class="carousel-item">
            <img class="w-100 h-100" src="img/product-3.jpg" alt="Image">
          </div>
          <div class="carousel-item">
            <img class="w-100 h-100" src="img/product-4.jpg" alt="Image">
          </div>
        </div>
        <a class="carousel-control-prev"  data-slide="prev">
          <i class="fa fa-2x fa-angle-left text-dark"></i>
        </a>
        <a class="carousel-control-next"  data-slide="next">
          <i class="fa fa-2x fa-angle-right text-dark"></i>
        </a>
      </div>
    </div>

    <div class="col-lg-7 pb-5">
      <h3 class="font-weight-semi-bold">Colorful Stylish Shirt</h3>
      <div class="d-flex mb-3">
        <div class="text-primary mr-2">
          <small class="fas fa-star"></small>
          <small class="fas fa-star"></small>
          <small class="fas fa-star"></small>
          <small class="fas fa-star-half-alt"></small>
          <small class="far fa-star"></small>
        </div>
        <small class="pt-1">(50 Reviews)</small>
      </div>
      <h3 class="font-weight-semi-bold mb-4">R150.00</h3>

      <div class="d-flex align-items-center mb-4 pt-2">
        <div class="input-group quantity mr-3" style="width: 130px;">
          <div class="input-group-btn">
            <button class="btn btn-primary btn-minus">
                                <i class="fa fa-minus"></i>
                                </button>
          </div>
          <input type="text" class="form-control bg-secondary text-center" value="1">
          <div class="input-group-btn">
            <button class="btn btn-primary btn-plus">
                                    <i class="fa fa-plus"></i>
                                </button>
          </div>
        </div>
        <button class="btn btn-primary px-3 ">
                        <a  class="btn btn-sm text-dark p-0"
                        data-id="1"
                        data-product-name="Colorful Stylish Shirt"
                        data-product-image="img/product-1.jpg"

                        ></a>
                        <i class="fa fa-shopping-cart mr-1 add-to-cart-btn" ></i> Add To Cart</button>
      </div>




$(document).ready(function() {
var cart = [];
var cartBadge = $(".cart-badge");
var cartTotal = $("#cart-total");
var cartItems = $("#cart-items");

// Initialize total to 0 when the page loads
var total = 0;

// Function to update the cart badge and cart total
function updateCartDisplay() {
  total = 0; // Reset total to 0 before recalculating
  cartItems.empty();

  for (var i = 0; i < cart.length; i++) {
    var item = cart[i];
    var itemTotal = item.price * item.quantity;
    total += itemTotal;

    cartItems.append("<li>" + item.name + " - Quantity: " + item.quantity + " - Total: R" + itemTotal.toFixed(2) + "</li>");
  }

  cartBadge.text(cart.length);
  cartTotal.text("R" + total.toFixed(2));
}

// Click event for the Add To Cart button
$(".add-to-cart").on("click", function() {
  var productId = 1;
  var productName = "Chick Cosmetics Makeup Brush + Sponge"; // Replace with the actual product name
  var productPrice = 145.00; // Replace with the actual product price
  var productQuantity = parseInt($(this).siblings(".quantity").find(".quantity-input").val());

  console.log("Product Price: " + productPrice);
  console.log("Product Quantity: " + productQuantity);

  var existingItemIndex = cart.findIndex(function(item) {
    return item.name === productName;
  });

  if (existingItemIndex !== -1) {
    // If the product is already in the cart, update the quantity
    cart[existingItemIndex].quantity += productQuantity;
    console.log("Product already in cart. Updated quantity: " + cart[existingItemIndex].quantity);
  } else {
    // Otherwise, add it to the cart
    cart.push({
      name: productName,
      price: productPrice,
      quantity: productQuantity
    });
    console.log("Product added to cart.");
  }

  // Update the cart badge and cart total
  updateCartDisplay();
});

// Click event for the "+" and "-" buttons
$(".btn-minus, .btn-plus").on("click", function() {
  var action = $(this).data("action");
  var inputField = $(this).siblings(".quantity-input");
  var currentQuantity = parseInt(inputField.val());

  if (action === "increase") {
    inputField.val(currentQuantity + 1);
  } else if (action === "decrease" && currentQuantity > 1) {
    inputField.val(currentQuantity - 1);
  }

  // Update the cart badge and cart total after quantity change
  updateCartDisplay();

  // Ensure the quantity change is reflected in the input field
  inputField.trigger("change");
});

// Rest of your code for updating the server-side cart and initializing the cart
// Function to update the server-side cart
function updateServerCart() {
  $.ajax({
    type: "POST",
    url: "makeup-cart.php",
    data: {
      action: 'updateCart',
      cart: JSON.stringify(cart)
    },
    success: function() {
      console.log("Server-side cart updated successfully.");
    }
  });
}

// Function to retrieve the cart from the server
function getServerCart() {
  $.ajax({
    type: "POST",
    url: "makeup-cart.php",
    data: {
      action: 'getCart'
    },
    success: function(data) {
      cart = JSON.parse(data);
      updateCartDisplay();
    }
  });
}

// Initialize the cart by retrieving it from the server
getServerCart();
});




});

 


Answers (2)