简体   繁体   English

Javascript检查在可接受的范围内

[英]Javascript check within acceptable range

I have a range high and a range low and I need to be able to display if the input number is within the acceptable range, or if it is higher or lower than the acceptable range. 我有一个高范围和一个低范围,并且我需要能够显示输入数字是否在可接受范围内,或者是高于还是低于可接受范围。

Currently, my javascript code looks like this but I keep getting the message saying it is an invalid entry. 目前,我的JavaScript代码看起来像这样,但我不断收到消息说这是无效的条目。

it needs to be able to handle decimal places as the high and low are based on user preference. 它需要能够处理小数位,因为高和低取决于用户的偏好。

    var highRange = 17.80;
    var lowRange = 6.90;
    var valueToCheck = (rText.value);

    function checkRange() {
        var msg = 'Invalid entry';
        if ((valueToCheck > 0.00) && (valueToCheck <= lowRange)) { msg = 'LOW'; }
        if ((valueToCheck > lowRange) && (valueToCheck <= highRange)) { msg = 'NORMAL'; }
        if ((valueToCheck > highRange)) { msg = 'HIGH'; }
        rangeValue = msg;
    }

I just don't understand why it isn't working, lol. 我只是不明白为什么它不起作用,大声笑。

Any help would be much appreciated :-) 任何帮助将非常感激 :-)

Try this. 尝试这个。

  var highRange = 17.80; var lowRange = 6.90; function checkRange() { var valueToCheck = document.getElementById('rText').value; var msg = 'Invalid entry'; if ((valueToCheck > 0.00) && (valueToCheck <= lowRange)) { msg = 'LOW'; } if ((valueToCheck > lowRange) && (valueToCheck <= highRange)) { msg = 'NORMAL'; } if ((valueToCheck > highRange)) { msg = 'HIGH'; } document.getElementById('rangeValue').innerHTML = msg; } 
 <input type="text" id="rText" > <input type="button" value="Validate" onclick="checkRange()"> <p id="rangeValue"></p> 
The problem was you put the valueToCheck outside the function.. Therefore when the page is loaded it already gets the null value of the input.. 问题是您将valueToCheck放在函数之外。因此,在加载页面时,它已经获取了输入的空值。

The valueToCheck must be inside the function in order to get what are the changes in the input.. valueToCheck必须在函数内部,以便获取输入中的更改。

使用parseFloat将您的字符串转换为浮点数。
var valueToCheck = parseFloat(rText.value);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM