Home > OS >  how to set add and subtract value min=0 and max=10 with jquery
how to set add and subtract value min=0 and max=10 with jquery

Time:10-02

how to set add and subtract input value using custom button wiht rule min=0 and max=10, it's almost similar to <input type="number" value="0" min="0" max="10" />, here is my code examples, i created button add and subtract to change the input value with jquery, but the value not have min and max rule, what should i do to create it?

$(function(){

  var x = $('input').val();
  
  $('#plus').click(function(){
    $('input').val(  x)
  });
  
  $('#minus').click(function(){
    $('input').val(--x)
  });

});
.n{display:flex}

input{margin:0 8px 0 8px}

.b{
padding: 4px;
background: yellow;
cursor: pointer;
}

.b:hover{
background: blue;
color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Quantity</p>
<div >
  <div id="minus" >
    minus
  </div>
  <input type="text" value='0'>
  <div id="plus" >
    plus
  </div>
</div>

CodePudding user response:

$(function(){

  var x = $('input').val();
  
  $('#plus').click(function(){
    $('input').val(x<10?  x:x)
  });
  
  $('#minus').click(function(){
    $('input').val(x>0?--x:x)
  });

});
.n{display:flex}

input{margin:0 8px 0 8px}

.b{
padding: 4px;
background: yellow;
cursor: pointer;
}

.b:hover{
background: blue;
color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Quantity</p>
<div >
  <div id="minus" >
    minus
  </div>
  <input type="text" value='0'>
  <div id="plus" >
    plus
  </div>
</div>

  • Related