我有以下HTML代码: 我想计算与每个复选框相关的价格,并在点击订单(按钮)后将其显示在文本区域中。请帮忙!
<div>
<form>
<fieldset > <legend>Resturant Menu:</legend>
<input type="checkbox" id = "menu" value="300">
<label> Chicken-------------------------- 300 AFN</label> <br>
<input type="checkbox" id = "menu" value="200">
<label> Chicken Baryani --------------- 200 AFN</label> <br>
<input type="checkbox" id = "menu" value="250">
<label> Chicken Kabab ----------------- 250 AFN</label> <br>
<input type="checkbox" id = "menu" value="100">
<label> Juice ----------------------------- 100 AFN</label> <br>
<input type="submit" id = "submit_btn" onclick = "calculate()">
</fieldset>
</form>
</div>
答案 0 :(得分:0)
这通常不是它在StackOverflow上的工作方式,你必须自己尝试修复它。但是,我很无聊,所以这里是HTML + Javascript的解决方案。
使用相同的名称声明多个ID是不好的做法,而是使用类。我改变了你的代码。您说您想在另一个字段中显示代码,因此不需要使用表单。
var menuItems = document.getElementsByClassName('menuItem');
var orderButton = document.getElementById('order_btn');
var totalArea = document.getElementById('total');
var afn = 0;
orderButton.addEventListener('click', function(e) {
e.preventDefault();
for (var i = 0; i < menuItems.length; i++) {
if (menuItems[i].checked) {
afn += +menuItems[i].value;
}
}
totalArea.innerHTML = "Total: " + afn + " AFN";
afn = 0;
});
<div>
<fieldset>
<legend>Resturant Menu:</legend>
<input type="checkbox" class="menuItem" value="300">
<label>Chicken-------------------------- 300 AFN</label>
<br>
<input type="checkbox" class="menuItem" value="200">
<label>Chicken Baryani --------------- 200 AFN</label>
<br>
<input type="checkbox" class="menuItem" value="250">
<label>Chicken Kabab ----------------- 250 AFN</label>
<br>
<input type="checkbox" class="menuItem" value="100">
<label>Juice ----------------------------- 100 AFN</label>
<br>
<button id="order_btn">Order</button>
</fieldset>
<p id="total">Total: 0 AFN</p>
</div>
答案 1 :(得分:0)
function calculate(){
var allMenuItem = $('#menuItem input[type=checkbox]');
var totalPrice = 0;
$.each(allMenuItem, function(key, element){
if($(this).is(":checked")){
totalPrice += parseFloat($(this).val());
}
});
alert("You order price is: "+ totalPrice + " Rs");
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<form>
<fieldset > <legend>Resturant Menu:</legend>
<div id="menuItem">
<input type="checkbox" id = "menu" value="300">
<label> Chicken-------------------------- 300 AFN</label> <br>
<input type="checkbox" id = "menu" value="200">
<label> Chicken Baryani --------------- 200 AFN</label> <br>
<input type="checkbox" id = "menu" value="250">
<label> Chicken Kabab ----------------- 250 AFN</label> <br>
<input type="checkbox" id = "menu" value="100">
<label> Juice ----------------------------- 100 AFN</label> <br>
<input type="button" value="Order" id = "submit_btn" onclick = "calculate()">
</div>
</fieldset>
</form>