问题描述
根据问题陈述,我们需要输入产品的数量和价格,然后在输出中显示总价 它显示 Parameter(id) 缺失和总价错误值 不显示结果的可能原因是什么
<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>```
解决方法
我认为问题可能在于您在以下行中遗漏了 totalvalue
周围的引号:
document.getElementById(totalprice).innerHTML=res;
应该是:
document.getElementById("totalprice").innerHTML=res;
编辑:
目前您正在尝试将 Html 节点解析为一个数字。您必须使用节点的 value
。
pric = parseFloat(document.getElementById("price").value);
qt = parseInt(document.getElementById("qty").value);
res = pric * qt;
document.getElementById("totalprice").innerHTML = res;
return false;
备注:当您将结果放在表单本身中时,它将在提交表单后立即处理。您可能需要考虑将其放在表单之外。
编辑 2:
如果你想坚持你目前的结构。您需要删除提交按钮的 id
并在 onsubmit
子句中添加返回。
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="billcalc.css" />
<script type="text/javascript">
function calculateTotalPrice() {
pric = parseFloat(document.getElementById("price").value);
qt = parseInt(document.getElementById("qty").value);
res = pric * qt;
document.getElementById("totalprice").innerHTML = res;
return false;
}
</script>
</head>
<h1>Bill Calculator</h1>
<form id="bill_from" onsubmit="return 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" /></td>
</tr>
</table>
</form>
</html>