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

@Carpe_diem

To modify the dropdown for quantity selection on the cart page, follow these steps:

Step 1: Update the Template File
Edit the cart-detailed-product-line.tpl file, located at themes/classic/templates/checkout/_partials/

Replace the relevant code with the following:

<select class="js-cart-line-product-quantity-select form-control product-quantity-dropdown" 
  data-product-id="{$product.id_product}" 
  data-current-qty="{$product.quantity}"
>
  {for $qty=$product.minimal_quantity to $product.quantity_available}
    <option value="{$qty}" {if $qty == $product.quantity}selected{/if}>{$qty}</option>
  {/for}
</select>

Step 2: Update the JavaScript
Add or update the JavaScript to handle dropdown changes dynamically:

document.addEventListener('DOMContentLoaded', function () {
    const dropdowns = document.querySelectorAll(".product-quantity-dropdown");

    dropdowns.forEach((dropdown) => {
        dropdown.addEventListener('change', async function () {
            const productId = this.dataset.productId;
            const selectedQuantity = parseInt(this.value);
            const currentQuantity = parseInt(this.dataset.currentQty);
            const quantityDifference = selectedQuantity - currentQuantity;
            // Determine the operation
            const operation = selectedQuantity > currentQuantity ? 'up' : 'down';
            try {
                const cartToken = prestashop.static_token;
                const baseUrl = prestashop.urls.pages.cart || "/cart";
                const updateUrl = `${baseUrl}?update=1&id_product=${productId}&token=${cartToken}`;
                const formData = new FormData();
                formData.append("ajax", "1");
                formData.append("action", "update");
                formData.append("qty", quantityDifference); // Quantity difference (positive or negative)
                formData.append("op", operation); // Operation: 'up' or 'down'
                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 && data.success) {
                    window.location.reload();
                } else {
                    alert(data.errors.join(", "));
                }
            } catch (error) {
                console.error("Error:", error);
                alert("An error occurred while updating the quantity.");
            }
        });
    });
});

Step 3:
In your PrestaShop admin panel, go to Advanced Parameters > Performance, and click Clear Cache.

Step 4:
Visit the front end to check on the cart page quantity selection dropdown. Review the screenshot for reference if needed.

We hope this solution works for you!
 

Link to comment
Share on other sites

5 hours ago, WebDesk Solution said:

@Carpe_diem

To modify the dropdown for quantity selection on the cart page, follow these steps:

Step 1: Update the Template File
Edit the cart-detailed-product-line.tpl file, located at themes/classic/templates/checkout/_partials/

Replace the relevant code with the following:

<select class="js-cart-line-product-quantity-select form-control product-quantity-dropdown" 
  data-product-id="{$product.id_product}" 
  data-current-qty="{$product.quantity}"
>
  {for $qty=$product.minimal_quantity to $product.quantity_available}
    <option value="{$qty}" {if $qty == $product.quantity}selected{/if}>{$qty}</option>
  {/for}
</select>

Step 2: Update the JavaScript
Add or update the JavaScript to handle dropdown changes dynamically:

document.addEventListener('DOMContentLoaded', function () {
    const dropdowns = document.querySelectorAll(".product-quantity-dropdown");

    dropdowns.forEach((dropdown) => {
        dropdown.addEventListener('change', async function () {
            const productId = this.dataset.productId;
            const selectedQuantity = parseInt(this.value);
            const currentQuantity = parseInt(this.dataset.currentQty);
            const quantityDifference = selectedQuantity - currentQuantity;
            // Determine the operation
            const operation = selectedQuantity > currentQuantity ? 'up' : 'down';
            try {
                const cartToken = prestashop.static_token;
                const baseUrl = prestashop.urls.pages.cart || "/cart";
                const updateUrl = `${baseUrl}?update=1&id_product=${productId}&token=${cartToken}`;
                const formData = new FormData();
                formData.append("ajax", "1");
                formData.append("action", "update");
                formData.append("qty", quantityDifference); // Quantity difference (positive or negative)
                formData.append("op", operation); // Operation: 'up' or 'down'
                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 && data.success) {
                    window.location.reload();
                } else {
                    alert(data.errors.join(", "));
                }
            } catch (error) {
                console.error("Error:", error);
                alert("An error occurred while updating the quantity.");
            }
        });
    });
});

Step 3:
In your PrestaShop admin panel, go to Advanced Parameters > Performance, and click Clear Cache.

Step 4:
Visit the front end to check on the cart page quantity selection dropdown. Review the screenshot for reference if needed.

We hope this solution works for you!
 

I will give it a try, thank you.

Link to comment
Share on other sites

22 hours ago, WebDesk Solution said:

@Carpe_diem

To modify the dropdown for quantity selection on the cart page, follow these steps:

Step 1: Update the Template File
Edit the cart-detailed-product-line.tpl file, located at themes/classic/templates/checkout/_partials/

Replace the relevant code with the following:

<select class="js-cart-line-product-quantity-select form-control product-quantity-dropdown" 
  data-product-id="{$product.id_product}" 
  data-current-qty="{$product.quantity}"
>
  {for $qty=$product.minimal_quantity to $product.quantity_available}
    <option value="{$qty}" {if $qty == $product.quantity}selected{/if}>{$qty}</option>
  {/for}
</select>

Step 2: Update the JavaScript
Add or update the JavaScript to handle dropdown changes dynamically:

document.addEventListener('DOMContentLoaded', function () {
    const dropdowns = document.querySelectorAll(".product-quantity-dropdown");

    dropdowns.forEach((dropdown) => {
        dropdown.addEventListener('change', async function () {
            const productId = this.dataset.productId;
            const selectedQuantity = parseInt(this.value);
            const currentQuantity = parseInt(this.dataset.currentQty);
            const quantityDifference = selectedQuantity - currentQuantity;
            // Determine the operation
            const operation = selectedQuantity > currentQuantity ? 'up' : 'down';
            try {
                const cartToken = prestashop.static_token;
                const baseUrl = prestashop.urls.pages.cart || "/cart";
                const updateUrl = `${baseUrl}?update=1&id_product=${productId}&token=${cartToken}`;
                const formData = new FormData();
                formData.append("ajax", "1");
                formData.append("action", "update");
                formData.append("qty", quantityDifference); // Quantity difference (positive or negative)
                formData.append("op", operation); // Operation: 'up' or 'down'
                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 && data.success) {
                    window.location.reload();
                } else {
                    alert(data.errors.join(", "));
                }
            } catch (error) {
                console.error("Error:", error);
                alert("An error occurred while updating the quantity.");
            }
        });
    });
});

Step 3:
In your PrestaShop admin panel, go to Advanced Parameters > Performance, and click Clear Cache.

Step 4:
Visit the front end to check on the cart page quantity selection dropdown. Review the screenshot for reference if needed.

We hope this solution works for you!
 

thank you it works

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...