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.
Colorful Stylish Shirt
(50 Reviews)
R150.00
$(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("" + item.name + " - Quantity: " + item.quantity + " - Total: R" + itemTotal.toFixed(2) + " ");
}
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();
});
});2 Replies
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Prasad RaveendranPosted Sep 27, 2023, 5:21 PM
It seems like you want to achieve two things:
Let's address each of these tasks:
Adding Items to the Cart and Updating the Cart Badge:
Your current code appears to handle adding items to the cart and updating the cart badge correctly. The click event for the "Add to Cart" button should add items to the
cartarray and then call theupdateCartDisplayfunction to update the cart badge and cart items list. Make sure you have assigned the class.add-to-cartto your "Add to Cart" button in your HTML code.2. Updating the Total Price when Clicking "+" and "-":
It seems like you want to dynamically update the total price when the user clicks the "+" and "-" buttons to adjust the quantity. To achieve this, you should update the
totalvariable within theupdateCartDisplayfunction after iterating through the cart items.Here's how you can modify your code to achieve this:
In the modified code:
The
totalvariable is updated within theupdateCartDisplayfunction to reflect the new total price based on the quantity changes.The click event for the "+" and "-" buttons updates the input field value and then calls
updateCartDisplayto update the cart total.This should ensure that your cart total is updated dynamically as you increase or decrease the quantity of items in the cart.
Make sure that your HTML markup is correctly structured with the necessary classes and attributes for this code to work as expected.
Amit ShrivastavaPosted Sep 27, 2023, 5:11 PM
I think you need to add something like this
hope this will help you