When performing laboratory work there was such a problem. The first field sets the lower limit of the range of numbers, and the second - the upper one. When you enter a number in the third field, the if / else should work.

The else statement does not work in this code, so even if the range is exceeded, a message about successful typing is displayed.

What could be wrong? I don’t see the problem.

var input = document.body.children[2]; var minrange = document.getElementById('minrange').value; var maxrange = document.getElementById('maxrange').value; var integerEEE = document.getElementById('integer').value; input.oninput = function() { if (integerEEE >= minrange && integerEEE <= maxrange) { alert("Введённое число входит в заданный диапазон. Валидация пройдена. Пожалуйста перезагрузите страницу и попробуйте снова."); } else { alert("Введённое число не входит в заданный диапазон. Пожалуйста перезагрузите страницу и попробуйте снова."); }; }; </script> 
  • 3
    the problem is that the values ​​of the variables do not change from the moment they are saved, therefore the same values ​​are always checked in the handler. Apparently - empty lines - Grundy Nov.

1 answer 1

Try to determine the input values ​​at the moment when the event handler is triggered.

 var input = document.body.children[2]; input.oninput = function() { var minrange = document.getElementById('minrange').value; var maxrange = document.getElementById('maxrange').value; var integerEEE = document.getElementById('integer').value; if (integerEEE >= minrange && integerEEE <= maxrange) { alert("Введённое число входит в заданный диапазон. Валидация пройдена. Пожалуйста перезагрузите страницу и попробуйте снова."); } else { alert("Введённое число не входит в заданный диапазон. Пожалуйста перезагрузите страницу и попробуйте снова."); }; }; 
  • "Semyon Semyonych!" Thank you, I blunted specifically. - Dmitry Marchenkov Nov.
  • @ Dmitriy Marchenkov, and it’s better to convert the number before the comparison - Grundy
  • @Grundy, i.e. will look something like this? var minrange = document.getElementById('minrange').value.ToInteger; - Dmitry Marchenkov
  • the string does not have the ToInteger property, but you can use parseInt : var minrange = parseInt(document.getElementById('minrange').value,10) - Grundy
  • @ Grundy, aha. It turns out here we pass in parseInt the value of our field and set the base of the decimal system, at the output getting an integer? - Dmitry Marchenkov Nov.