新手在这里努力学习
我试图检查输入到我的表单中的数据,如果输入到第二或第三输入的数据不是数字(即字母顺序),则向用户显示信息不是数字。我正在使用“isNaN”函数来实现这个功能,但根据我在Google、Stack和其他地方看到的内容,它并不像我所希望的那样起作用。我尝试过'isNaN‘和'!isNaN',没有一个触发了我的脚本中希望发生的事件。
这是我正在尝试的JavaScript :如果(空(thisForm.epiName,"Episode名称留空。请输入提交集的名称,以便我们可以大胆地去检查您的结果!“)){返回假};
if(empty(thisForm.rsTot,"Red shirt total left blank. Please enter the total estimated number of Starfleet officers wearing red shirts to appear in this episode so we can boldly go and check your results!")){return false;}
if(empty(thisForm.reRemaining,"Red shirts surviving left blank. Please enter the number of Starfleet officers to survive this episode so we can boldly go and check your results!")){return false;}
if(isNaN(thisForm.rsTot,"Info entered is not a number, we can not boldly check your result!")){return false;}
if(isNaN(thisForm.reRemainder,"Info entered is not a number, we can not boldly check your result!")){return false;}
return true;//if all is passed, submit!网站网址:OOPform.php
发布于 2014-05-29 16:00:23
isNaN只接受一个参数。此外,您应该注意到,在被检查之前,参数是被胁迫成一个数字的。
为了避免意外的结果,最好先检查一下是否是一个数字。
function safeIsNaN(num) {
if (typeof num !== "number") {
return true; //this is Not-a-Number
}
return isNaN(num);
}发布于 2014-05-29 16:33:33
首先,例如您的代码中的thisForm.rsTot是一个HTMLElement,它永远不可能是一个数字。修复方法应该是这样的:
if(isNaN(+(thisForm.rsTot.value))) {
alert("Info entered is not a number, we can not boldly check your result!");
return false;
}一元+将其操作数转换为数字,如果操作失败,则将操作数转换为NaN,然后由isNaN检查该操作数。我更喜欢一元+,因为parseFloat()从字符串中返回可能的前导数字,如果字符串中甚至有一个非数字字符,一元+总是给出NaN。
注意,您必须使用input的值,而不是元素本身。此值始终是一个字符串。
检查变量是否为数字的一般方法:
function isNumber (n) {
return (!isNaN(+n) && isFinite(n));
}发布于 2014-05-29 16:02:52
您需要将表单字段的值传递给isNaN,另外,正如前面提到的注释一样,isNaN函数只接受一个参数。您需要一些其他方式来向用户显示错误消息:
if (isNaN(thisForm.reTot.value)) {
// call some function to show error message, which you will need to create
return false;
}https://stackoverflow.com/questions/23937354
复制相似问题