Jump to content

Dropdown for quantity on cart page


Recommended Posts

Hi guys,

In a project I need to change the input field with a dropdown field on the cart page. My goal is to create a dropdown that updates the quantity depending on the selected value of the dropdown.

If a user has 5 items of product A in his cart. He decides he wants 7 so he picks seven in the dropdown and the cart should update to 7. But in the end he wants only 2 items and it needs to change the quantity in the cart to 2. 

Here is my try. It increases the quantity without a problem, but I can't figure out how to fix decreasing, everything I try it increases by the number you want to decrease. To make it clear, if the quantity is 5 and I change it to 2 it increases the quantity to 8. 
Here is my whole code:

document.addEventListener("DOMContentLoaded", function () {
    const quantitySelects = document.querySelectorAll(".js-cart-line-product-quantity-select");

    quantitySelects.forEach(function (select) {
        let isUpdating = false;

        select.addEventListener("change", async function (event) {
            event.preventDefault();

             if (isUpdating) return;
  const selectedQuantity = parseInt(this.value, 10);
            const currentQuantity = parseInt(this.dataset.currentQty, 10); // Current quantity in the dataset
            const productId = this.dataset.productId;
            const maxQty = parseInt(this.dataset.maxQty, 10); // Max available quantity

                if (selectedQuantity > maxQty) {
                alert(`Maximum available quantity is ${maxQty}`);
                this.value = this.dataset.currentQty; // Revert to previous value
                return;
            }

             const quantityInput = document.querySelector(`input.js-cart-line-product-quantity[data-product-id="${productId}"]`);
            if (!quantityInput) return;

            const cartToken = prestashop.static_token;

             this.disabled = true;
            isUpdating = true;

            try {
               const baseUrl = prestashop.urls.pages.cart || "/cart";
                const updateUrl = `${baseUrl}?update=1&id_product=${productId}&token=${cartToken}`;

                let quantityDifference = selectedQuantity - currentQuantity;

              
               const formData = new FormData();
                formData.append("ajax", "1");
                formData.append("action", "update");
                formData.append("id_product", productId);
                formData.append("id_customization", "0");
                formData.append("qty", quantityDifference); // Send the difference (negative for decrease, positive for increase)
                formData.append("token", cartToken);

               
                 const response = await fetch(updateUrl, {
                    method: "POST",
                    body: formData,
                    headers: {
                        "X-Requested-With": "XMLHttpRequest",
                    },
                });

                if (!response.ok) throw new Error("Network response was not ok");

                const data = await response.json();
               

                if (data.hasError) {
                    alert(data.errors.join(", "));
                    this.value = this.dataset.currentQty; 
                } else {
                 
                    quantityInput.value = selectedQuantity;
                    this.dataset.currentQty = selectedQuantity; 
                    window.location.reload(); 
                }
            } catch (error) {
                console.error("Error:", error);
                alert("An error occurred while updating the quantity");
                this.value = this.dataset.currentQty; 
            } finally {
                this.disabled = false;
                isUpdating = false;
            }
        });
    });
});

Here is my cart-detailed-product-line.tpl

              <div class="cart-line-product-quantity-wrapper">
                        <select class="js-cart-line-product-quantity-select form-control"
                            data-product-id="{$product.id_product}" data-current-qty="{$product.quantity}"
                            data-max-qty="{$product.quantity_available}" name="quantity_{$product.id_product}">
                            {for $qty=$product.minimal_quantity to $product.quantity_available}
                                <option value="{$qty}" {if $qty == $product.quantity}selected="selected" {/if}>
                                    {$qty}
                                </option>
                            {/for}
                        </select>
                        <input class="js-cart-line-product-quantity form-control" type="hidden"
                            data-down-url="{$product.down_quantity_url}" data-up-url="{$product.up_quantity_url}"
                            data-update-url="{$product.update_quantity_url}" data-product-id="{$product.id_product}"
                            value="{$product.quantity}" name="product_quantity_{$product.id_product}"
                            min="{$product.minimal_quantity}" />
                    </div>

Can someone please help me out 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...