Javascript输入返回NaN或未定义

Javascript输入返回NaN或未定义,javascript,html,Javascript,Html,我正在制作一个小费计算器,我想让用户看到小费金额。我遇到的问题是输出显示为“NaN”或“undefined”。我尝试过修改我的代码,但我总是得到同样的结果 函数calculateIP(){ var billInput=document.getElementById('bill'); var tipPercentage=document.getElementById('tip'); var tipercentagecalc=(tipercentage/100); var tipAmount=(比

我正在制作一个小费计算器,我想让用户看到小费金额。我遇到的问题是输出显示为“NaN”或“undefined”。我尝试过修改我的代码,但我总是得到同样的结果

函数calculateIP(){
var billInput=document.getElementById('bill');
var tipPercentage=document.getElementById('tip');
var tipercentagecalc=(tipercentage/100);
var tipAmount=(比尔*蒂珀森塔格计算).toFixed(2);
tipAmount=tipAmount.toString();
document.getElementById('display_text')。innerHTML='Tip=$',+tipAmount;
};

法案:$

小费:%


您忘记获取字段的值。因为没有属性
.value
,它返回
HTMLObject

function calculateTip() {
    var billInput = parseFloat(document.getElementById('bill').value);
    var tipPercentage = parseFloat(document.getElementById('tip').value);
    var tipPercentageCalc = (tipPercentage / 100);
    var tipAmount = (bill * tipPercentageCalc).toFixed(2);
    tipAmount = tipAmount.toString();
    document.getElementById('display_text').innerHTML = 'Tip = $', + tipAmount;

};

您将
billInput
tipPercentage
读取为HTML元素对象,而不是用户键入的文本,这将是它们的
.value
属性。

在声明变量
billInput
TipperEntage
时,您正在加载元素而不是元素值。请尝试使用以下代码:

var billInput = document.getElementById('bill').value;
var tipPercentage = document.getElementById('tip').value;
函数calculateIP(){
//获取textbox元素的VALUE属性
//parseInt将把它们转换成数字,如果它们还没有。
//如果它们不是数字,你就不能在数学中使用它们。
var billInput=parseInt(document.getElementById('bill').value);
var tipPercentage=parseInt(document.getElementById('tip').value);
var tipercentagecalc=(tipercentage/100);
变量tipAmount=(billInput*TipperEntageCalc);
//isNaN代表“不是一个数字”
//这将检查tipAmount是否不是一个数字
//如果不是,我们只需将其设置为数字0
if(伊斯南(蒂帕蒙特)){
tipAmount=0;
}
//将数字连接到字符串时,无需将其转换为字符串。
//它将自动转换
document.getElementById('display_text')。innerHTML='Tip=$'+tipAmount;
};

法案:$

小费:%


您还需要使用
parseFloat()
将字符串转换为数字。下面的答案会有所帮助,只是一个建议,不过在将来,编程的乐趣之一是调试您自己的代码。进行更改与其说是调试,不如说是反复试验。下一次尝试插入调试器和/或断点,并逐行遍历,真正思考每行中发生的情况。提供错误的详细信息以及所提供代码上修复的内容有助于轻松评估答案。
function calculateTip() {
// get the VALUE property of the textbox elements
// parseInt will turn them into numbers if they're not already.
// if they are not numbers you cannot use them in math.

  var billInput = parseInt(document.getElementById('bill').value);
  var tipPercentage = parseInt(document.getElementById('tip').value);
  var tipPercentageCalc = (tipPercentage / 100);
  var tipAmount = (billInput * tipPercentageCalc);

// isNaN stands for "is Not a Number"
// this checks if tipAmount is not a number
// if it is not we simply set it to the number 0
if (isNaN(tipAmount)) {
    tipAmount = 0;
  }

  // when you concatenate a number to a string you do not need to turn it into a string.
  // it will automatically be converted
  document.getElementById('display_text').innerHTML = 'Tip = $' + tipAmount;

};