PrNum文本框只能输入整数,PrPrice与TotalPrice能输入小数点后2位数,给出示例代码
时间: 2024-05-15 10:17:43 浏览: 16
好的,我明白了。以下是一个简单的示例代码:
HTML代码:
```
<label>商品数量:</label>
<input type="number" id="PrNum" min="1" step="1">
<label>商品单价:</label>
<input type="number" id="PrPrice" min="0.01" step="0.01">
<label>总价:</label>
<input type="number" id="TotalPrice" min="0.01" step="0.01" readonly>
```
JavaScript代码:
```
// 获取输入框
var PrNum = document.getElementById("PrNum");
var PrPrice = document.getElementById("PrPrice");
var TotalPrice = document.getElementById("TotalPrice");
// 监听输入事件
PrNum.addEventListener("input", calculateTotalPrice);
PrPrice.addEventListener("input", calculateTotalPrice);
// 计算总价
function calculateTotalPrice() {
var num = PrNum.value;
var price = PrPrice.value;
// 处理数量
num = parseInt(num);
if (isNaN(num) || num < 1) {
num = 1;
PrNum.value = num;
}
// 处理单价
price = parseFloat(price);
if (isNaN(price) || price < 0.01) {
price = 0.01;
PrPrice.value = price.toFixed(2);
} else {
price = price.toFixed(2);
PrPrice.value = price;
}
// 计算总价
var totalPrice = num * price;
TotalPrice.value = totalPrice.toFixed(2);
}
```
这段代码通过监听输入框的输入事件,实时计算出总价,并限制了文本框只能输入符合要求的数值。对于PrNum,只能输入整数;对于PrPrice和TotalPrice,可以输入小数点后2位数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)