Tùng Nguyễn
Tùng Nguyễn

Reputation: 103

How to make limitation on value input field with js

I'm learning js and I need help to solve this problem. My problem is that I try to limit the maximum and minimum value of the input, the adding and subtracting buttons are fine, however, I want when I input numbers directly in the input field if the number greater or smaller than the limitation it will automatically return the limit range.

for example, my limit range is from 1 to 10, when I input 11 into the input field it will return 10 immediately.

I have html code:

<button type="button" class="btn btn-default minus">
    <i class="fas fa-minus"></i>
</button>
<input id="qty2" type="text" value="1" class="qty" size="5" name="quantity" class="form-control"/>
<button type="button" class="btn btn-default btn-icon add">
   <i class="fas fa-plus"></i>
</button>

and my js code

<script>
    $(function () {
        $('.add').on('click',function(){
            var $qty=$(this).closest('p').find('.qty');
            var currentVal = parseInt($qty.val());
            if (!isNaN(currentVal) && currentVal < 10) {
                $qty.val(currentVal + 1);
            }
        });
        $('.minus').on('click',function(){
            var $qty=$(this).closest('p').find('.qty');
            var currentVal = parseInt($qty.val());
            if (!isNaN(currentVal) && currentVal > 1) {
                $qty.val(currentVal - 1);
            }
        });
    });
</script>

Upvotes: 0

Views: 943

Answers (2)

pensum
pensum

Reputation: 1019

You should be using the html input tag of type="number" if you expect a user to write numbers, and you don't need javascript to limit the min and max values. You simply need to add the attributes to the html tag instead.

<input id="myNumber" type="number" min="1" max="10">


Considering that you asked how to do it with javascript, here is a demonstration with the onchange event

function myFunction() {
  var x = document.getElementById("myNumber").value;
  document.getElementById("demo").innerHTML = "You selected: " + x;
}
<p>Choose a number between 1 and 10</p>
<input id="myNumber" type="number" onchange="myFunction()">

<p id="demo"></p>

Upvotes: 1

Wenbo
Wenbo

Reputation: 1452

You can use onchange event. https://www.w3schools.com/jsref/event_onchange.asp Like

<input id="qty2" type="text" value="1" class="qty" size="5" name="quantity" class="form-control" onchange=onInputChange(this)/>

...
function onInputChange(input) {
   if (input.value > max) {
     input.value = max;
   } else if (input.value < min) {
      input.value = min;
  }
}
...

I did not verify the code, but it should be like this. You also can add events like onblur to verify the value of the input.

Upvotes: 1

Related Questions