在前端开发中,我们可以使用多个单选按钮来让用户选择不同的选项,并计算总价。以下是一个实现该功能的步骤:
根据以上步骤,以下是一个示例代码:
HTML:
<form id="orderForm">
<input type="radio" name="size" value="small"> Small
<input type="radio" name="size" value="medium"> Medium
<input type="radio" name="size" value="large"> Large
<input type="checkbox" name="toppings" value="cheese"> Cheese
<input type="checkbox" name="toppings" value="pepperoni"> Pepperoni
<input type="checkbox" name="toppings" value="mushrooms"> Mushrooms
<button type="button" onclick="calculateTotal()">Calculate Total</button>
</form>
Total Price: <span id="totalPrice"></span>
JavaScript:
function calculateTotal() {
var size = document.querySelector('input[name="size"]:checked').value;
var toppings = document.querySelectorAll('input[name="toppings"]:checked');
var sizePrice = 0;
switch (size) {
case 'small':
sizePrice = 5;
break;
case 'medium':
sizePrice = 10;
break;
case 'large':
sizePrice = 15;
break;
}
var toppingsPrice = 0;
for (var i = 0; i < toppings.length; i++) {
toppingsPrice += 2;
}
var totalPrice = sizePrice + toppingsPrice;
document.getElementById('totalPrice').textContent = totalPrice;
}
在上述代码中,我们创建了一个包含单选按钮和复选框的表单。当用户点击"Calculate Total"按钮时,调用calculateTotal函数。该函数首先获取选中的单选按钮和复选框的值,并根据选择的不同选项计算总价。最后,将计算得到的总价显示给用户。
这只是一个简单的示例,实际的实现可能会更复杂,具体取决于你的业务需求和设计。在实际项目中,你可能还需要考虑数据验证、错误处理、用户体验等因素。
领取专属 10元无门槛券
手把手带您无忧上云