How to set a minimum step value for add to cart quantity?

How to set a minimum step value for add to cart quantity?

Logozeep
New Member
4 0 0

Hi there!

 

I'm trying to set a minimum step value for add to cart, but it looks like the 'value' parameter isn't working as it should. The goal is - customers only be able to add 3, 6, 9, .. items to cart, but now the system allows them to add any value after the minimum value (which is 3 items) - 4, 5 and so on.

 

Store URL: https://3-wines.com/

There is the code I have applied in order to achieve my goal

 

 

<input id="product-quantity-{{ product_form_id }}" type="number" name="quantity" value="3" min="3" step="3"
      form="{{ product_form_id }}" aria-label="{{ 'products.product.quantity.label' | t }}">

 

Replies 3 (3)

NomtechSolution
Astronaut
1245 113 160

The step attribute in the HTML <input> element defines the stepping interval for number inputs. However, it does not enforce a minimum step value or restrict users from manually entering values between steps. To achieve your goal of allowing customers to add only 3, 6, 9, and so on items to the cart, you'll need to use some additional JavaScript code.

Here's an example of how you can accomplish this:

  1. Locate the JavaScript file or section in your theme where you can add custom code.
  2. Add the following JavaScript code:

 

 

document.addEventListener('DOMContentLoaded', function() {
  var quantityInput = document.getElementById('product-quantity-{{ product_form_id }}');
  
  quantityInput.addEventListener('change', function() {
    var value = parseInt(quantityInput.value);
    var minStep = 3;
    
    if (value % minStep !== 0) {
      // Round up the quantity to the next valid step
      var roundedValue = Math.ceil(value / minStep) * minStep;
      quantityInput.value = roundedValue;
    }
  });
});
​

 

 

  • Make sure to replace {{ product_form_id }} with the actual ID or class of the product form input field on your website.

    This code listens for changes in the quantity input field and checks if the entered value is a multiple of 3. If it's not, it rounds up the quantity to the next valid step (e.g., 4 becomes 6, 5 becomes 6). This ensures that only quantities that are multiples of 3 are added to the cart.

Logozeep
New Member
4 0 0

Thanks, but I cant find the class name I need to paste instead of {{ product_form_id }}, because I dont know the Java Scriprt.

Logozeep
New Member
4 0 0

I have tried everything, this code doesn't work for me