我有一个基于点数系统的测验,每个单选按钮都存储在我正在遍历的数组中。根据为每个问题选择的无线电,用户会根据该无线电的价值获得一定数量的积分。问题是,如果用户改变主意并取消选择收音机/更改答案,我希望能够删除收音机的要点。
for (var i = 0; i < allRadios.length; i++) {
allRadios[i].addEventListener('change', (e)=>{
let radio = e.target;
if (radio.checked) {
totalScoreMain = totalScoreMain + parseInt(radio.getAttribute('value'));
}
});
}
答案 0 :(得分:0)
您可以简单地收集change
函数中所有选中的单选按钮,然后计算这些选中的单选按钮的值:
var totalScoreMain = 0,
allRadios = document.querySelectorAll('input[type="radio"]');
for (var i = 0; i < allRadios.length; i++) {
allRadios[i].addEventListener('change', (e) => {
totalScoreMain = 0;
let checkedRadios = document.querySelectorAll('input[type="radio"]:checked');
checkedRadios.forEach(function(checkedRadio) {
totalScoreMain += parseInt(checkedRadio.getAttribute('value'));
});
console.log(totalScoreMain);
});
}
<div>
<input name='1_1' type="radio" value="10"> 10
<input name='1_1' type="radio" value="20"> 20
</div>
<div>
<input name='1_2' type="radio" value="30"> 30
<input name='1_2' type="radio" value="40"> 40
<input name='1_2' type="radio" value="50"> 50
</div>
<div>
<input name='1_3' type="radio" value="35"> 35
<input name='1_3' type="radio" value="45"> 45
<input name='1_3' type="radio" value="25"> 25
</div>