尝试使用JavaScript通过复选框循环计算总价

尝试使用JavaScript通过复选框循环计算总价,javascript,html,Javascript,Html,我的目标是,当单击复选框时,其数据价格应添加到total变量中,然后此变量应显示在total price文本框中,但是,当前在单击复选框时不会更新值 下面是一个互动示例,展示了它当前的工作方式/外观: const form=document.getElementById('bookingForm'); const total=document.getElementsByName[0]('total'); document.getElementById(“bookingForm”).addEve

我的目标是,当单击复选框时,其数据价格应添加到total变量中,然后此变量应显示在total price文本框中,但是,当前在单击复选框时不会更新值

下面是一个互动示例,展示了它当前的工作方式/外观:

const form=document.getElementById('bookingForm');
const total=document.getElementsByName[0]('total');
document.getElementById(“bookingForm”).addEventListener(“单击”,函数(e){
如果(e.target.name==“event[]”){
设total=0;
[…document.querySelectorAll('input[data price][type=checkbox]'))].forEach(函数(框){
如果(复选框){
合计+=+box.dataset.price;
}//如果
})
document.querySelector(“[name=total]”)。innerHTML=total.toFixed(2);
}
})

选择事件
事件1
10.50
活动2
5
总价
总价


对于
输入
元素,您应该使用
而不是
innerHTML

const form=document.getElementById('bookingForm');
const total=document.getElementsByName('total')[0];
document.getElementById(“bookingForm”).addEventListener(“单击”,函数(e){
如果(e.target.name==“event[]”){
设total=0;
[…document.querySelectorAll('input[data price][type=checkbox]'))].forEach(函数(框){
如果(复选框){
合计+=+box.dataset.price;
}//如果
})
document.querySelector(“[name=total]”)。value=total.toFixed(2);
}
})

选择事件
事件1
10.50
活动2
5
总价
总价

const form=document.getElementById('bookingForm');
const total=document.getElementsByName('total');
var chksbox=document.querySelectorAll('.chkEvent');
forEach(函数(chk){
chk.addEventListener(“单击”,函数(e){
var合计=0;
chksbox.forEach(函数(框){
如果(复选框)
总计+=+box.dataset.price
});
document.querySelector(“[name=total]”)。value=total.toFixed(2);
});
});

选择事件
事件1
价格:10.50
活动2
价格:5.00
总价
总价


尝试使用
const total=document.getElementsByName('total')[0]
另一种方法是
document.getElementsByName[0]('total')