AL DI AL DI - 3 months ago 9
Javascript Question

How to add 1 to a value in an input field with javascript on click?

Good morning everyone,

I have a shopping cart and I want to implement an update quantities per item.. Let me show you that code maybe it will be easier to explain.

HTML:

<div class="custom-quantity-input">
<input type="text" name="quantity" class="" value="<?php echo $items['qty']; ?>">
<a href="#" onclick="return false;" class="quantity-btn quantity-input-up"><i class="fa fa-angle-up"></i></a>
<a href="#" onclick="return false;" class="quantity-btn quantity-input-down"><i class="fa fa-angle-down"></i></a>
</div>


I want that when user click on the link add-one to increase the amount on the input field and when they click #decrease to reduce by one the amount on the input field just visually no Ajax or anything.

I don't know much of JavaScript that's why I seek your help.

Thank you in advance guys!

Answer

$(function(){
  $(".quantity-input-up").click(function(){
    var inpt = $(this).parents(".custom-quantity-input").find("[name=quantity]");
    var val = parseInt(inpt.val());
    if ( val < 0 ) inpt.val(0);
    inpt.val(val+1);
  });
  $(".quantity-input-down").click(function(){
    var inpt = $(this).parents(".custom-quantity-input").find("[name=quantity]");
    var val = parseInt(inpt.val());
    if ( val < 0 ) inpt.val(0);
    if ( val == 0 ) return;
    inpt.val(val-1);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="custom-quantity-input">
  <input type="number" min="0" name="quantity" class="" value="5">
     <a href="#" class="quantity-btn quantity-input-up"><i class="fa fa-angle-up">+</i></a>
     <a href="#" class="quantity-btn quantity-input-down"><i class="fa fa-angle-down">-</i></a>
</div>

<div class="custom-quantity-input">
  <input type="number" min="0" name="quantity" class="" value="9">
     <a href="#" class="quantity-btn quantity-input-up"><i class="fa fa-angle-up">+</i></a>
     <a href="#" class="quantity-btn quantity-input-down"><i class="fa fa-angle-down">-</i></a>
</div>

<div class="custom-quantity-input">
  <input type="number" min="0" name="quantity" class="" value="200">
     <a href="#" class="quantity-btn quantity-input-up"><i class="fa fa-angle-up">+</i></a>
     <a href="#" class="quantity-btn quantity-input-down"><i class="fa fa-angle-down">-</i></a>
</div>

Comments