Help with Javascript comparison operators

4

Good afternoon, I'm doing a job, of which I'm going to have several forms with a minimum and maximum number and I'm trying to create a check function and avoid inserting numbers out of range through the keyboard, my function was this way

$(':input[type="number"]').on('keyup', function(event) {
  var id = this.id;
  var min = document.getElementById(id).getAttribute('min');
  var max = document.getElementById(id).getAttribute('max');

  verificaTypeNumber(id, min, max);
});

function verificaTypeNumber(idInput, minValue, maxValue) {
  var aux = document.getElementById(idInput).value;

  if (aux == null || aux < minValue) {
    document.getElementById(idInput).value = minValue;
  } else if (aux > maxValue) {
    document.getElementById(idInput).value = maxValue;
  }

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="number" id="Teste" min="10" max="999" value="10">

When you enter a value below the range (in the example less than "10") the function works and enters within if() , but for a value above the range (above 999), it does not work and does not enter of else if()

    
asked by anonymous 20.11.2016 / 17:31

1 answer

3

The .value of an input and the min and max attributes you are reading are strings . And because of this he is comparing text and not numbers.

Notice in my answer that I use Number to convert text ( strings ) into numbers and so your logic already works.

I also changed what is passed to the function, so instead of calling% 5% of times, you do not call any and you use the document.getElementById(idInput) which is the element you want.

$(':input[type="number"]').on('keyup', function(event) {
  var min = Number(this.getAttribute('min'));
  var max = Number(this.getAttribute('max'));

  verificaTypeNumber(this, min, max);
});

function verificaTypeNumber(el, minValue, maxValue) {
  var aux = Number(el.value);

  if (aux == 0 || aux < minValue) {
    el.value = minValue;
  } else if (aux > maxValue) {
    el.value = maxValue;
  }

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="number" id="Teste" min="10" max="999" value="10">
    
20.11.2016 / 17:53