用js写简易商品表单求总价和数量
时间: 2024-04-04 12:34:30 浏览: 15
可以使用JavaScript来实现一个简易商品表单,求总价和数量,具体实现步骤如下:
1. 在HTML中创建一个表单,包含商品名称、价格、数量等输入框,以及求总价和数量的按钮。
2. 在JavaScript中获取表单中的商品信息,计算每个商品的总价和数量,并将结果显示在页面上。
下面是一个示例代码,可以根据实际需求进行修改:
HTML代码:
```
<form>
<div>
<label>商品名称:</label>
<input type="text" id="name1" value="商品1">
<label>价格:</label>
<input type="number" id="price1" value="10">
<label>数量:</label>
<input type="number" id="quantity1" value="1">
<label>小计:</label>
<span id="subtotal1"></span>
</div>
<div>
<label>商品名称:</label>
<input type="text" id="name2" value="商品2">
<label>价格:</label>
<input type="number" id="price2" value="20">
<label>数量:</label>
<input type="number" id="quantity2" value="2">
<label>小计:</label>
<span id="subtotal2"></span>
</div>
<div>
<button type="button" id="calculate">计算总价和数量</button>
<label>总数量:</label>
<span id="totalQuantity"></span>
<label>总价:</label>
<span id="totalPrice"></span>
</div>
</form>
```
JavaScript代码:
```
var calculateBtn = document.getElementById('calculate');
calculateBtn.addEventListener('click', function() {
var quantity1 = parseInt(document.getElementById('quantity1').value);
var price1 = parseFloat(document.getElementById('price1').value);
var subtotal1 = quantity1 * price1;
document.getElementById('subtotal1').innerHTML = subtotal1.toFixed(2);
var quantity2 = parseInt(document.getElementById('quantity2').value);
var price2 = parseFloat(document.getElementById('price2').value);
var subtotal2 = quantity2 * price2;
document.getElementById('subtotal2').innerHTML = subtotal2.toFixed(2);
var totalQuantity = quantity1 + quantity2;
document.getElementById('totalQuantity').innerHTML = totalQuantity;
var totalPrice = subtotal1 + subtotal2;
document.getElementById('totalPrice').innerHTML = totalPrice.toFixed(2);
});
```
这段代码通过事件监听器,当“计算总价和数量”按钮被点击时,获取表单中的商品信息,计算每个商品的小计和总数量,然后计算总价和总数量,并将结果显示在页面上。你可以根据实际需求进行修改。