Berk Kaya
Berk Kaya

Reputation: 470

JS increase/decrease multiple input number variables

I have been trying toincrease and decrease value of 'val' class and i'll use them more than once in one page. Also i need to set MIN and MAX values for them.

   <input type="button" value="-" class="decreaseVal">
   <input type="number" min ="1" max="22" value="20" class="val" disabled>
   <input type="button" value="+" class="increaseVal">


   // JS CODE THAT I TRY
   $(".decreaseVal").click(function() {
      var num = $(this).next('input').val();
   });


   $(".increaseVal").click(function() {
      var num = $(this).prev('input').val();
   });

I can get their values but i am not able to change them. Any advice guys?

Upvotes: 2

Views: 2738

Answers (1)

Pavan Teja
Pavan Teja

Reputation: 3202

try this

$(".decreaseVal").click(function() {
  var input_el=$(this).next('input');
  var v= input_el.val()-1;
  if(v>=input_el.attr('min'))
  input_el.val(v)
});


$(".increaseVal").click(function() {
  var input_el=$(this).prev('input');
  var v= input_el.val()*1+1;
  if(v<=input_el.attr('max'))
  input_el.val(v)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="-" class="decreaseVal">
<input type="number" min="1" max="22" value="20" class="val" disabled>
<input type="button" value="+" class="increaseVal">

Upvotes: 6

Related Questions