Help with Javascript comparison operators

Asked

Viewed 146 times

4

Good Afternoon, I am doing a job, of which I will have several forms with a minimum and maximum number and I want to create a check function and avoid inserting numbers out of the track by 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>
<input type="number" id="Teste" min="10" max="999" value="10">

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

1 answer

3


The .value of an input and attributes min and max that you’re reading are strings. And because of that he’s comparing text and not numbers.

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

I also changed what’s passed to the function, so you can call it document.getElementById(idInput) 5 times, don’t call any and use the this 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>
<input type="number" id="Teste" min="10" max="999" value="10">

Browser other questions tagged

You are not signed in. Login or sign up in order to post.