如果isNaN,如何将变量的内容更改为零

时间:2011-10-13 00:41:43

标签: javascript

  

可能重复:
  When I press enter I get isNaN, but the value is a number

我上周日上交了作业。由于isNaN值被返回到Total textbox,我被送回给我进行修正。我认为这就是编程要做的事情。相反,根据她的说法,“isNaN函数将检查变量并确定变量是否包含非数字数据,然后下一个语句将变量的内容更改为零,”这让我感到困惑。任何建议这是代码。 *回报;”在进行更改之前,语句不是语法错误。以下是上传文件的链接:ciswebs.smc.edu/cis54/tyson_schweidel/homework2.htm

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Price Calculator</title>
<script type="text/javascript">

function fixOrder()
{
var numPrice = parseFloat(document.getElementById("cost").value);
var taxP = parseFloat(document.getElementById("tax").value);
var total = parseFloat(document.getElementById("total").value);

}

if (isNaN(numPrice)){

    alert("Sorry,you must enter a numeric value to place order");

if (isNaN(taxP))
    alert("Sorry, you must enter a numeric tax value to continue");
    return; //gets syntax error
}


var tax = (numPrice * taxP)/100;{
var total = numPrice + tax;
numPrice = 0;
taxP = 0;
    document.getElementById("total").value = "$" + total.toFixed(2);
return; //gets syntax error
}
</script>

</head>

<body bgcolor="#00f3F1">


<h1 align="left">Price Calculator</h1>

<form name="form">
<p>
Price:  <input type="text" id="cost" name="cost" value="" onchange="fixOrder();"/>
</p>
<p>
Tax: &nbsp;
<input type="text" id="tax" name="tax" value="" onchange="fixOrder();"/>
</p>
<p>
Total: 
<input type="text" id="total" name="total" value="" disabled="disabled();"/>
</p>
</form>

2 个答案:

答案 0 :(得分:3)

你的格式搞砸了,导致你在它真正做任何事情之前退出函数fixOrder:

function fixOrder() {
    var numPrice = parseFloat(document.getElementById("cost").value);
    var taxP = parseFloat(document.getElementById("tax").value);
    var total = parseFloat(document.getElementById("total").value);



    if (isNaN(numPrice)) {
        alert("Sorry,you must enter a numeric value to place order");
        return; //gets syntax error
    }

    if (isNaN(taxP)) {
        alert("Sorry, you must enter a numeric tax value to continue");
        return;
    }

    var tax = (numPrice * taxP) / 100;
    var total = numPrice + tax;
    numPrice = 0;
    taxP = 0;
    document.getElementById("total").value = "$" + total.toFixed(2);
    return; //gets syntax error
}

看看有多容易阅读?您可以将原始代码缩减为:

document.getElementById("total").value = "$NaN";

答案 1 :(得分:2)

isNaN()函数尝试检查它们时,您的变量不在范围内。