[英]javascript calculate total from dropdown and checkbox not updating to 0 when on another select box
I have a script that calculate total based on dropdown boxes and check boxes , I have main drop down menu with 我有一个基于下拉框和复选框计算总数的脚本,我有带有
<select id="type" name="menu">
<option value="">Service Needed</option>
<option value="kite">Car Wash & Detailing</option>
<option value="user">Mechanic visit</option>
<option value="elect">Electrican visit</option>
<option value="tyre">Tyre Service</option>
<option value="bat">Battery Service</option>
</select>
SUB MENU
<select id="type2" name="buyername" class="form-control input-lg form-el calculate" >
<option data-price="0" value="">-- Select --</option>
<option data-price="100" value="kite1">Car Wash exterior</option>
<option data-price="150" value="kite1">Car Wash In & Out</option>
<option data-price="1000" value="kite2">Full Detailing</option>
</select>
now when you select service like car wash & detailing then choose car wash exterior from sub menu the total price shown is 100, then after i click on another service like mechanic visit the price still on 100 , it should be 0 again as the price menu is deselected 现在,当您选择诸如洗车及保养之类的服务,然后从子菜单中选择洗车外观时,总价为100,然后在我单击另一项服务(如机修工)后,价格仍为100,价格菜单应再次为0被取消选择
here is the script 这是脚本
<script type='text/javascript'>//<![CDATA[
$(function(){
$("select.calculate").on("change", calc);
$("input[type=checkbox].calculate").on("click", calc);
function calc() {
var basePrice = 0;
newPrice = basePrice;
// You need to loop over, not only the selected option, but also the checked checboxes
$("select.calculate option:selected,input[type=checkbox].calculate:checked").each(function (idx, el) {
newPrice += parseInt($(el).data('price'), 10);
});
newPrice = newPrice.toFixed(2);
$("#item-price").html(newPrice);
}
});
</script>
any idea how to fix this.?? 任何想法如何解决这个问题。
You need a reset event handler on your main menu, something like this: 您需要在主菜单上设置一个重置事件处理程序,如下所示:
$("#type").on("change", function() {
$("select.calculate option").eq(0).prop('selected', true);
calc();
});
When you change your main menu (triggering a change event) this will reset your sub menu to the first option ( --select--
) and rerun your calc function, zeroing the output. 更改主菜单(触发更改事件)时,这会将子菜单重置为第一个选项(
--select--
),然后重新运行calc函数,将输出清零。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.