1 回答
TA贡献2051条经验 获得超10个赞
这不是您的完整解决方案,而是一个工作示例,说明如何完成。我想,你可以先用它。
document.getElementById("a").addEventListener('click', function(event) {
event.preventDefault();
deselectAll();
checkUncheckElement(1, true);
checkUncheckElement(2, true);
calculatePrice();
});
document.getElementById("b").addEventListener('click', function(event) {
event.preventDefault();
deselectAll();
checkUncheckElement(3, true);
checkUncheckElement(4, true);
calculatePrice();
});
function deselectAll() {
var elements = document.querySelectorAll('#main > form > input');
for(var a = 0; a < elements.length; a++) {
elements[a].checked = false;
}
}
function checkUncheckElement(id, value) {
document.getElementById(id).checked = value;
}
function calculatePrice() {
var elements = document.querySelectorAll('#main > form > input');
var price = 0;
for(var a = 0; a < elements.length; a++) {
if(elements[a].checked == true) {
price = price + parseInt(document.getElementById('price' + elements[a].id).innerHTML);
}
}
document.getElementById('total').innerHTML = '$' + price;
}
<h1>Show checkboxes:</h1>
<div style="border:1px solid">
<form action="/action_page.php">
<input type="checkbox" id="a"> A <br>
<input type="checkbox" id="b"> B <br>
</form>
</div>
<div style="border:1px solid; margin-top:20px;" id="main">
<form action="/action_page.php">
<input type="checkbox" id="1"> 1 $<span id="price1">20</span><br>
<input type="checkbox" id="2"> 2 $<span id="price2">20</span><br>
<input type="checkbox" id="3"> 3 $<span id="price3">20</span><br>
<input type="checkbox" id="4"> 4 $<span id="price4">20</span><br>
<input type="checkbox" id="5"> 5 $<span id="price5">20</span><br>
<input type="checkbox" id="6"> 6 $<span id="price6">20</span><br>
</form>
</div>
<br><br>
Total: <span id="total"></span>
添加回答
举报