1 回答
TA贡献1848条经验 获得超2个赞
您需要在这里结合使用 PHP 和 Javascript。后端需要 PHP 以对象的形式从您的数据库中获取数据,如果选择了一个选项,则 Javascript 使用该对象在您的页面上显示价格。
请注意,您需要进行 ajax 调用以将您的对象从 PHP 转换为 Javascript,这可以使用现代浏览器的XHR、jQuery.ajax()或Fetch API来完成。
这是一个如何完成的示例:
var validityButtons = document.getElementsByName('validity');
var foodTimeButtons = document.getElementsByName('foodtime');
var prices = {
breakfast: {
daily: 120,
weekly: 110,
monthly: 100
},
lunch: {
daily: 150,
weekly: 130,
monthly: 120
},
dinner: {
daily: 150,
weekly: 130,
monthly: 120
},
};
function calculatePrice() {
var price = 0;
var currentOption;
var showPrice = document.getElementById('price');
/* Iterate through radio buttons to get the checked one */
validityButtons.forEach(function(button) {
if (button.checked === true) {
currentOption = button.value;
}
});
/* Iterate through checkboxes to calculate price depending on selected options */
foodTimeButtons.forEach(function(button) {
if (button.checked) {
switch(button.value) {
case 'breakfast':
price += prices.breakfast[currentOption];
break;
case 'lunch':
price += prices.lunch[currentOption];
break;
case 'dinner':
price += prices.dinner[currentOption];
break;
default:
break;
}
}
});
/* Show price */
showPrice.innerText = price;
}
/* Fire a function when radio button gets clicked */
validityButtons.forEach(function(button) {
button.addEventListener('change', calculatePrice);
});
/* Fire a function when checkboxes are clicked */
foodTimeButtons.forEach(function(button) {
button.addEventListener('change', calculatePrice);
});
/* Calculate the price based on selected options on page load */
calculatePrice();
Select your package validity:
<label>
<input type="radio" name="validity" value="daily" checked> Daily
</label>
<label>
<input type="radio" name="validity" value="weekly"> Weekly
</label>
<label>
<input type="radio" name="validity" value="monthly"> Monthly
</label>
<br><br>
Select your food time:
<label>
<input type="checkbox" name="foodtime" value="breakfast" checked> Breakfast
</label>
<label>
<input type="checkbox" name="foodtime" value="lunch"> Lunch
</label>
<label>
<input type="checkbox" name="foodtime" value="dinner"> Dinner
</label>
<br><br>
Your price: <strong id="price"></strong>
- 1 回答
- 0 关注
- 141 浏览
添加回答
举报