计算javascript上的提示。我的代码有什么问题?

时间:2016-01-10 09:15:19

标签: javascript html

继续展示" NaN"而且我不知道为什么。文本字段应显示其输入的"晚餐服务员多少钱的10%和20%?"

<body>
<script type="text/javascript">
        function tipp()
        {
        var tip = alert("You Calculated The tip " + document.form1.textfield.value + " in the Textfield.");
        tip = parseFloat(tip);
        var tf2 = tip * .10;
        var tf3 = tip * .20;
        document.form1.textfield2.value = tf2;
        document.form1.textfield3.value = tf3;
        }
</script>
    <form name="form1">
        How much was dinner,waiter?<input type="text" name="textfield" id="tip"><br><br>
        <input type="button" onClick = "tipp()" value="Calculate Tip"><br><br>
        10% <input type="text" id="textfield2"><br><br>
        20%<input type="text3" id="textfield3"><br><br>
    </form>
</body>

1 个答案:

答案 0 :(得分:2)

alert没有返回值,因此tip将为undefinedparseFloat(undefined)NaNNaN的所有数学计算都会产生NaN

不是使用alert的返回值,而是从您的字段中获取值:

var tip = parseFloat(document.getElementById("tip").value);

示例(我删除了警告,我不知道您要在那里展示什么;另外,我在所有字段中使用了getElementById):

&#13;
&#13;
function tipp() {
  var tip = parseFloat(document.getElementById("tip").value);
  var tf2 = tip * .10;
  var tf3 = tip * .20;
  document.getElementById("textfield2").value = tf2;
  document.getElementById("textfield3").value = tf3;
}
&#13;
<form name="form1">
  How much was dinner,waiter?
  <input type="text" name="textfield" id="tip">
  <br>
  <br>
  <input type="button" onClick="tipp()" value="Calculate Tip">
  <br>
  <br>10%
  <input type="text" id="textfield2">
  <br>
  <br>20%
  <input type="text3" id="textfield3">
  <br>
  <br>
</form>
&#13;
&#13;
&#13;