我正在做的事情:
我有一个javascript程序,当单击一个按钮时,从一个表单中的4个文本框中获取4个字符串,并将这些字符串输出到格式化的文本区域.
function testResults(form){
var errorhandle1 = parseInt(document.myForm.Item_Code.value);
var errorhandle2 = parseInt(document.myForm.Item_Cost.value);
var errorhandle3 = parseInt(document.myForm.Quantity.value);
//above variables are for error handling.
var d = " ";
var subtotal = parseInt(form.Item_Cost.value) * parseInt(form.Quantity.value);
var subtotalValue = parseInt(document.myForm.Subtotal.value);
var testVar = "Item Code: " + form.Item_Code.value + d +
"Item Name: " + form.Item_Name.value + d +
"Item Cost: " + form.Item_Cost.value + d +
"Quantity: " + form.Quantity.value + '\n';
document.myForm.myTextarea.value += testVar;
document.myForm.Subtotal.value = parseInt(subtotal) + subtotalValue;
document.myForm.Sales_Tax.value = document.myForm.Subtotal.value * salestax;
document.myForm.Total.value = parseInt(document.myForm.Subtotal.value) + parseFloat(document.myForm.Sales_Tax.value);
}
Run Code Online (Sandbox Code Playgroud)
上面的代码工作得很好,并且完全符合我希望它为我的程序范围做的事情.
try {
if ((isNaN(errorhandle3) == true) || (isNaN(errorhandle2) == true)) {
throw "Error1";
}
} catch (e) {
if (e == "Error1") {
alert("Error! You must enter a number into the qty and cost fields!");
}
}
Run Code Online (Sandbox Code Playgroud)
我试图用try ... catch块来完成的只是为了确保这一点
document.myForm.Item_Code.value
document.myForm.Item_Cost.value
document.myForm.Quantity.value
Run Code Online (Sandbox Code Playgroud)
实际上是数字.
try ... catch语句在每次运行程序时触发,并不关心我在相应的文本框中放置的内容.我将非常感谢对此的任何和所有见解!
另外:我查看了这两个链接,但无法理解我的问题. javascript parseInt为空字符串返回NaN http://www.w3schools.com/jsref/jsref_isnan.asp
你的根本问题是isNaN()测试是否值NaN.它不会测试字符串是否是正确的数字.它有一些强制规则试图处理字符串,但这实际上不是它的设计目的.
您可以在此处查看测试某些内容是否可以解析为有效数字的方法:在JavaScript中验证十进制数字 - IsNumeric()
值得仔细阅读那里的好答案中的详细信息,但它可归结为类似于此类的东西,这比您需要的要多,但它是通用的:
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Run Code Online (Sandbox Code Playgroud)
而且,没有理由在代码中使用异常,所以你可以这样做:
if (!isNumber(errorhandle3) || !(isNumber(errorhandle2)) {
alert("Error! You must enter a number into the qty and cost fields!");
}
Run Code Online (Sandbox Code Playgroud)
此外,在您的代码中,某些.Value属性看起来可能应该是.value(小写).