Shopify Increase and decrease product 2 by 2

77 views Asked by At

I would like that on my shopify product page, the quantity selector adds 2 by 2 or decreases 2 by 2 the quantity sent in the cart. The starting quantity must also be 2. All that I succeeded, but where I block, it is that when we have already clicked on "+" and that we go down to 2, we can still click on "-" which makes us fall to 1 and it distorts everything... How could I make that on the quantity 2 one can no longer click on the "-"?

Thank you very much for your help here is my current code:

                {% if product.tags contains 'Liquidation' and product.type contains 'Chaise' %}
                 
<div class="ProductForm__QuantitySelector" {{ block.shopify_attributes }}>
  {% if block.settings.show_label %}
    <span class="ProductForm__Label">{{ 'product.form.quantity' | t }}:</span>
  {% endif %}

  <div class="QuantitySelector QuantitySelector--large">
  <button type="button" class="QuantitySelector__Button Link Link--secondary" data-action="decrease-quantity" disabled>{% render 'icon' with 'minus' %}</button>
  <input type="text" id="quantity-input" class="QuantitySelector__CurrentQuantity" pattern="[0-9]*" name="quantity" value="2" aria-label="{{ 'product.form.quantity' | t }}">
  <button type="button" class="QuantitySelector__Button Link Link--secondary" data-action="increase-quantity">{% render 'icon' with 'plus' %}</button>
</div>

</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
  const decreaseButton = document.querySelector('[data-action="decrease-quantity"]');
  const increaseButton = document.querySelector('[data-action="increase-quantity"]');
  const quantityInput = document.getElementById('quantity-input');

  const updateDecreaseButtonState = () => {
    decreaseButton.disabled = parseInt(quantityInput.value) === 2;
  };

  // Mise à jour initiale de l'état du bouton de diminution
  updateDecreaseButtonState();

  decreaseButton.addEventListener('click', function() {
    let quantity = parseInt(quantityInput.value);
    if (quantity > 2) {
      quantity -= 1;
      quantityInput.value = quantity;
    } else {
      quantity -= 0;
      quantityInput.value = quantity;
    }
    updateDecreaseButtonState();
  });

  increaseButton.addEventListener('click', function() {
    let quantity = parseInt(quantityInput.value);
    quantity += 1;
    quantityInput.value = quantity;
    updateDecreaseButtonState();
  });

  quantityInput.addEventListener('change', function() {
    let quantity = parseInt(this.value);
    if (isNaN(quantity) || quantity < 2) {
      this.value = 2;
    } else if (quantity % 2 !== 0) {
      this.value = quantity + (2 - quantity % 2);
    }
    updateDecreaseButtonState();
  });
});



</script>

                    {% else %}
                  
                  <div class="ProductForm__QuantitySelector" {{ block.shopify_attributes }}>
                    {% if block.settings.show_label %}
                      <span class="ProductForm__Label">{{ 'product.form.quantity' | t }}:</span>
                    {% endif %}
                    
                  <div class="QuantitySelector QuantitySelector--large">
                      {% assign quantity_minus_one = line_item.quantity | minus: 1 %}
                      <button type="button" class="QuantitySelector__Button Link Link--secondary" data-action="decrease-quantity">{% render 'icon' with 'minus' %}</button>
                      <input type="text" class="QuantitySelector__CurrentQuantity" pattern="[0-9]*" name="quantity" value="1" aria-label="{{ 'product.form.quantity' | t }}">
                      <button type="button" class="QuantitySelector__Button Link Link--secondary" data-action="increase-quantity">{% render 'icon' with 'plus' %}</button>
                    </div>
                  </div>
        {% endif %}

1

There are 1 answers

0
steph On

Well, finally, I did otherwise, I chose not to make the shopping cart button clickable in case of odd numbers and to leave it clickable if it is even. Moreover I made display run message in case of odd number, here is my solution for those interested.

{% comment %}----------------------Check if the product is a chair otherwise we do normally----------------{% endcomment %}
                
                {% if product.tags contains 'Liquidation' and product.type contains 'Chaise' %}
                  
{% comment %}----------------------END Check if the product is a chair otherwise we do normally----------------{% endcomment %}

                  <p style="color: red;" id="messageAlert"></p>
                  <button type="submit" data-use-primary-button="{% if use_primary_button %}true{% else %}false{% endif %}" class="ProductForm__AddToCart ButtonCustom {% if product.selected_or_first_available_variant.available and use_primary_button %}CustomButtonAddToCart{% else %}Button--secondary{% endif %} Button--full" {% if product.selected_or_first_available_variant.available %}data-action="add-to-cart"{% else %}disabled="disabled"{% endif %}>
                      {% if product.selected_or_first_available_variant.available %}
                        <span>{% if product.template_suffix == 'pre-order' %}{{ 'product.form.pre_order' | t }}{% else %}{{ 'product.form.add_to_cart' | t }}{% endif %}</span>

                        {% if block.settings.show_price_in_button %}
                          <span class="Button__SeparatorDot"></span>
                          <span>{{ product.selected_or_first_available_variant.price | money }}</span>
                        {% endif %}
                      {% else %}
                        {{ 'product.form.sold_out' | t }}
                      {% endif %}
                    </button>

                    
{% comment %}----------------------JS to check that the chairs are selling well by pairs otherwise it deactivates the buy button----------------{% endcomment %}
                  <script>
                    
                      document.addEventListener('DOMContentLoaded', function() {
                        const decreaseButton = document.querySelector('[data-action="decrease-quantity"]');
                        const increaseButton = document.querySelector('[data-action="increase-quantity"]');
                        const quantityInput = document.querySelector('.QuantitySelector__CurrentQuantity');
                        const addToCartButton = document.querySelector('[data-action="add-to-cart"]');
                      
                        const updateAddToCartButtonState = () => {
                          let selectedQuantity = parseInt(quantityInput.value);
                          // Désactive le bouton si la quantité n'est pas un nombre pair
                          addToCartButton.disabled = selectedQuantity % 2 !== 0;
                         // Affiche le message si la quantité est impaire
                          if (selectedQuantity % 2 !== 0) {
                            document.getElementById("messageAlert").textContent = "La quantité doit être un nombre pair.";
                            document.getElementById("messageAlert").style.visibility = "visible";
                          } else {
                            document.getElementById("messageAlert").style.visibility = "collapse";
                          }
                        };
                      
                        // Initialisation
                        updateAddToCartButtonState();
                      
                        // Écouteurs d'événements pour les boutons
                        decreaseButton.addEventListener('click', function() {
                          setTimeout(function() {
                            updateAddToCartButtonState();
                          }, 10);
                        });
                      
                        increaseButton.addEventListener('click', function() {
                          setTimeout(function() {
                            updateAddToCartButtonState();
                          }, 10);
                        });
                      
                        // Écouteur d'événements pour les changements manuels dans l'input
                        quantityInput.addEventListener('change', updateAddToCartButtonState);
                      });
                  </script>
{% comment %}----------------------END JS to check that the chairs are selling well by pairs otherwise it deactivates the buy button----------------{% endcomment %}