John Smith
John Smith

Reputation: 67

Increment / Decrement quantity number on WooCommerce using jQuery

I'm using the following to add + and - buttons to my WooCommerce store. It's working, except once clicked it will change every item quantity in the cart instead of just the specific product. I can't seem to solve it.

Here's the HTML:

<div class="quantity">
<label for="quantity5432">Quantity</label>
<input type="number" id="quantity5432" class="qty" step="1" min="0" name="cart[73d][qty]" value="0">
</div>

<div class="quantity-nav">
<div class="quantity-button add-action add-up">+</div>
<div class="quantity-button add-action add-down">-</div>
</div>

And here's the jQuery

$(document).ready(function() {
  const minus = $('.add-down');
  const plus = $('.add-up');
  const input = $('.qty');
  minus.click(function(e) {
    e.preventDefault();
    var value = input.val();
    if (value > 1) {
      value--;
    }
    input.val(value);
  });

  plus.click(function(e) {
    e.preventDefault();
    var value = input.val();
    value++;
    input.val(value);
  })
});```

Upvotes: 0

Views: 2148

Answers (1)

matthias_h
matthias_h

Reputation: 11416

You can adjust your script to target the specific input with the class .qty by selecting this input in the minus and add click() events based on the location of the click.

$(document).ready(function() {
  const minus = $('.add-down');
  const plus = $('.add-up');
  minus.click(function(e) {
    e.preventDefault();
    const input = $(this).closest(".quantity-nav").prev(".quantity").find(".qty");
    var value = input.val();
    if (value > 1) {
      value--;
    }
    input.val(value);
  });

  plus.click(function(e) {
    e.preventDefault();
    const input = $(this).closest(".quantity-nav").prev(".quantity").find(".qty");
    var value = input.val();
    value++;
    input.val(value);
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="quantity">
  <label for="quantity5432">Quantity</label>
  <input type="number" id="quantity5432" class="qty" step="1" min="0" name="cart[73d][qty]" value="0">
</div>
<div class="quantity-nav">
  <div class="quantity-button add-action add-up">+</div>
  <div class="quantity-button add-action add-down">-</div>
</div>
<div class="quantity">
  <label for="quantity5433">Quantity</label>
  <input type="number" id="quantity5433" class="qty" step="1" min="0" name="cart[73e][qty]" value="0">
</div>

<div class="quantity-nav">
  <div class="quantity-button add-action add-up">+</div>
  <div class="quantity-button add-action add-down">-</div>
</div>

Upvotes: 2

Related Questions