Increase/Decrease Input Number With JavaScript In HTML

Increase/Decrease Input Number With JavaScript In HTML!

If you follow this post you can easily understand how to increase/decrease the input number with plus/minus buttons. For icons, we used BoxIcons.

Step 01: HTML Code

<div class="input-counter">
     <span class="minus-btn"><i class="bx bx-minus"></i></span>
     <input type="text" value="1">
     <span class="plus-btn"><i class="bx bx-plus"></i></span>
</div>

Step 02: CSS Code

.input-counter {
  max-width: 150px;
  min-width: 150px;
  text-align: center;
  position: relative;
}
.input-counter span {
  top: 0;
  width: 40px;
  height: 100%;
  font-size: 15px;
  cursor: pointer;
  line-height: 50px;
  position: absolute;
  color: var(--paragraphColor);
  background-color: transparent;
  -webkit-transition: var(--transition);
  transition: var(--transition);
}
.input-counter span.minus-btn {
  left: 0;
  border-right: 1px solid #eeeeee;
}
.input-counter span.plus-btn {
  right: 0;
  border-left: 1px solid #eeeeee;
}
.input-counter span:hover {
  color: var(--primaryColor);
}
.input-counter input {
  outline: 0;
  width: 100%;
  height: 47px;
  display: block;
  text-align: center;
  color: var(--blackColor);
  border: 1px solid #eeeeee;
  background-color: var(--whiteColor);
  font-size: 17px;
  font-weight: 600;
}
.input-counter input::placeholder {
  color: var(--blackColor);
}

Step 03: JavaScript Code

$('.input-counter').each(function() {
  var spinner = jQuery(this),
  input = spinner.find('input[type="text"]'),
  btnUp = spinner.find('.plus-btn'),
  btnDown = spinner.find('.minus-btn'),
  min = input.attr('min'),
  max = input.attr('max');
  btnUp.on('click', function() {
    var oldValue = parseFloat(input.val());
    if (oldValue >= max) {
      var newVal = oldValue;
    } else {
      var newVal = oldValue + 1;
     }
     spinner.find("input").val(newVal);
     spinner.find("input").trigger("change");
    });
    btnDown.on('click', function() {
      var oldValue = parseFloat(input.val());
      if (oldValue <= min) {
        var newVal = oldValue;
      } else {
        var newVal = oldValue - 1;
      }
      spinner.find("input").val(newVal);
      spinner.find("input").trigger("change");
   });
});

I hope this article will help you how to learn easily to Increase/Decrease Input Number.

If you have any queries, please let me know in the comments section.

Till then!

Happy Coding!

Leave a Reply

Your email address will not be published. Required fields are marked *