简体   繁体   English

无法获取isNaN函数以使其正常工作

[英]Can't get isNaN function to work properly

I've created three text boxes. 我创建了三个文本框。 The first two text boxes are for two numbers (for subtraction). 前两个文本框用于两个数字(用于减法)。 The result will appear in the third text box. 结果将出现在第三个文本框中。 I'm trying to make it so that if the user puts in a letter instead of a number, an alert happens. 我正在尝试这样做,以便如果用户输入字母而不是数字,则会发生警报。

Right now, the isNaN isn't working. 目前,isNaN无法正常工作。 Whenever I put anything in the first or second textbox, it alerts, regardless of number or letter. 每当我在第一个或第二个文本框中放入任何内容时,它都会发出警报,无论数字或字母如何。 Here's my code. 这是我的代码。

function myFunction() {
    var x = document.getElementById("taxFree"); //textbox 1
    var y = document.getElementById("prodCost"); //textbox 2
    var res = document.getElementById("salesMargin"); //Result textbox

     // If x or y is Not a Number, send alert to user
    if (isNaN(x) || isNaN(y)) {
        alert("Numers only!");
        return;
    } 
    res.value = x.value - y.value;
}

Thanks in advance! 提前致谢!

尝试检查inputvalue

if (isNaN(x.value) || isNaN(y.value)) {

The isNaN function tells you if a value equals to the special value NaN . isNaN函数告诉您值是否等于特殊值NaN If it is a string it will try to parse it befor. 如果是字符串,它将尝试对其进行解析。 isNaN will not return true for every value that is not a number, for example isNaN(true) === false . isNaN不会为每个非数字值返回true,例如isNaN(true) === false

The other thing is that you try to call isNaN on the input element itself, not its value. 另一件事是您尝试在输入元素本身而不是其值上调用isNaN Try this instead: 尝试以下方法:

 function myFunction() { var taxFree = document.getElementById("taxFree"); var prodCost = document.getElementById("prodCost"); var salesMargin = document.getElementById("salesMargin"); //Result textbox var x = parseFloat(taxFree.value); var y = parseFloat(prodCost.value); // If x or y is Not a Number, send alert to user if (isNaN(x) || isNaN(y)) { alert("Numers only!"); return; } salesMargin.value = x - y; } 
 <input id="taxFree" value="15"> <input id="prodCost" value="10"> <input id="salesMargin" value="x"> <button onclick="myFunction()">Go!</button> 

I must say this method will not work if you want to know if the entered input is a number or not. 我必须说,如果您想知道输入的输入是否为数字,则此方法将不起作用。

Try this , this function will only accept numbers from 0 to 9, nothing else at all even decimals not allowed. 尝试此操作,此函数将只接受0到9之间的数字,即使是小数也不允许。 It does so by checking the entered input's char 通过检查输入的字符来实现

code: onkeypress='return event.charCode >= 48 && event.charCode <= 57' 代码: onkeypress='return event.charCode >= 48 && event.charCode <= 57'

just add this line to your input as follows: 只需将此行添加到您的输入中,如下所示:

<input id="taxfree" onkeypress='return event.charCode >= 48 && event.charCode <= 57'>

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

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