Javascript 为什么我得不到正确的总价?
根据问题陈述,我们需要输入产品的数量和价格,然后在输出中显示总价 它显示缺少参数(id)和总价的错误值 不显示结果的可能原因是什么Javascript 为什么我得不到正确的总价?,javascript,html,css,html5-canvas,Javascript,Html,Css,Html5 Canvas,根据问题陈述,我们需要输入产品的数量和价格,然后在输出中显示总价 它显示缺少参数(id)和总价的错误值 不显示结果的可能原因是什么 <html> <head> <meta charset="utf-8"> <link rel="stylesheet" href="billcalc.css"> <script type = &qu
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="billcalc.css">
<script type = "text/javascript">
function calculateTotalPrice()
{ pric=parseFloat(document.getElementById("price"));
qt=parseInt(document.getElementById("qty"));
res=pric*qt;
document.getElementById(totalprice).innerHTML=res;
return false;
}
</script>
</head>
<h1>Bill Calculator</h1>
<form onsubmit="calculateTotalPrice()">
<table>
<tr>
<td><label for="productName">Product Name</label></td>
<td><input type="text" placeholder="Product Name" id="productName" name="productName" required></td>
</tr>
<tr>
<td><label for="price">Product Price in Rs.</label></td>
<td><input type="number" placeholder="Product Price" id="price" min="0" required/></td>
</tr>
<tr>
<td><label>Quantity</label></td>
<td><input type="number" placeholder="Enter Quantity" id="qty" min="1" required></td>
</tr>
<tr>
<td><label for="totalprice">Total Price in Rs.</label></td>
<td><output type="number" id="totalprice" for="price qty" required>
</output></td>
</tr>
<tr>
<td colspan="2"><input type="submit" id="submit" ></td>
</tr>
</table>
</form>
</html>```
函数calculateTotalPrice()
{pric=parseFloat(document.getElementById(“price”);
qt=parseInt(document.getElementById(“数量”);
res=pric*qt;
document.getElementById(totalprice).innerHTML=res;
返回false;
}
账单计算器
品名
产品价格(卢比)。
量
总价(卢比)。
```
我认为问题可能是您缺少以下行中的totalvalue
周围的引号:
document.getElementById(totalprice).innerHTML=res;
应该是:
document.getElementById(“totalprice”).innerHTML=res;
编辑:
当前,您正在尝试将Html节点解析为一个数字。您必须使用节点的值
pric=parseFloat(document.getElementById(“price”).value);
qt=parseInt(document.getElementById(“数量”)值);
res=pric*qt;
document.getElementById(“totalprice”).innerHTML=res;
返回false;
备注:当您将结果放入表单本身时,它将在提交表单后立即处理。您可能想考虑将其放置在窗体之外。
编辑2:
如果你想坚持目前的结构。您需要删除submit按钮的id
,并在onsubmit
子句中添加一个返回
函数calculateTotalPrice(){
pric=parseFloat(document.getElementById(“price”).value);
qt=parseInt(document.getElementById(“数量”)值);
res=pric*qt;
document.getElementById(“totalprice”).innerHTML=res;
返回false;
}
账单计算器
品名
产品价格(卢比)。
量
总价(卢比)。
忘记了引号:document.getElementById('totalprice').innerHTML=res代码>document.getElementById('price')=>document.getElementById('price')。值谢谢!但我仍然面临同样的问题。还有其他原因吗?我想我发现了这个问题!请查看上面的“我的编辑”,并在帮助您解决问题时将其标记为正确。在输入数字时表示感谢,但获取“totalprice”组件值计算是错误的,在说明中:“缺少必需的参数(id)。当网页希望从另一页传递参数时,会发生此错误(通过post或cookie),但它无法执行此操作。有时,当用户会话因不活动而超时时,或者当需要该强制参数的URL直接在URL栏中键入或从浏览器书签中调用时,会发生这种情况,例如SCORM Player页面不是从课程页面中的链接启动的。”这就是测试用例失败的原因虽然结果是正确的,但在结果显示后不久,屏幕就会消失,并显示上述注释。非常感谢您的努力。我不确定这个错误消息,但正如我在回答中提到的,当包含结果的标签放置在因此,当表单提交时,它将像其他字段一样被重置。您应该考虑将其放置在窗体之外或使用预期的标签()。