Javascript increase and decrease button to be multiple of 2, 5 and 10

My Javascript doesn't seem to work properly. My increase and decrease buttons don't work and I want to know how to make some of them to only work with multiples of 2, 5 or 10. (Example multiple of 5: I can only order 5, 10, 15.. so the increase and decrease buttons must only add accordingly.)

I have 7 products, all similar to this one, just the name, price, and image that differs.

$('.like-btn').on('click', function() {
  $(this).toggleClass('is-active');
});

$('.minus-btn').on('click', function(e) {
  e.preventDefault();
  var $this = $(this);
  var $input = $this.closest('div').find('input');
  var value = parseInt($input.val());

  if (value > 1) {
    value = value - 1;
  } else {
    value = 0;
  }

  $input.val(value);

});

$('.plus-btn').on('click', function(e) {
  e.preventDefault();
  var $this = $(this);
  var $input = $this.closest('div').find('input');
  var value = parseInt($input.val());

  if (value < 100) {
    value = value + 1;
  } else {
    value = 100;
  }

  $input.val(value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="item">
  <div class="buttons">
    <span class="delete-btn"></span>
    <span class="like-btn"></span>
  </div>

  <div class="image">
    <img src="item-3.png" alt="" />
  </div>

  <div class="description">
    <span>Super Star Destroyer</span>
    <span>Brown</span>
  </div>

  <div class="quantity">
    <button class="plus-btn" type="button" name="button">
      <img src="plus.svg" alt="" />
    </button>
    <input type="text" name="name" value="1">
    <button class="minus-btn" type="button" name="button">
      <img src="minus.svg" alt="" />
    </button>
  </div>

  <div class="total-price">$4570000</div>
</div>

1 answer

  • answered 2019-08-07 16:30 WBT

    First, fix the syntax error:
    (value & amp; lt; 100) should probably be (value < 100) and
    (value & amp; gt; 1) should probably be (value >= 1).

    Keep in mind for the future that if you copy a code snippet from somewhere, you should try to understand what it does (every line!) before using it.

    You could use <input name="myName" type="number" step="5"> in your HTML, as one solution. This might help you solve the immediate problem in a concise manner.

    Alternatively, in the lines that say value = value + 1; and value = value - 1; you could change the 1 to a 5 (or a constant called STEP_SIZE defined once at the top of the file). This strategy might help you learn more about Javascript and improve your programming skills.

    Either way, good luck!