In the image, I first selected the first two checkboxes and clicked to calculate. Then, I unchecked the second one and clicked again to calculate, and it gave me still both values and total price. Also, when I click on the clear button and check it again, it does the same thing but with the price “0”.
My code:
const calcButton = document.getElementById('calc-button');
const clearButton = document.getElementById('clear-button');
const result = document.getElementById('result');
let currentValue = 0;
let totalPrice = 0;
let exams = [];
function getCheckboxValue(event) {
const checkboxValue = event.target.value;
if (event.target.checked) {
currentValue = checkboxValue;
getPrice(currentValue);
getName(currentValue);
} else {
currentValue = '';
}
}
function getPrice() {
let price = document.querySelector(`#price${currentValue}`);
let priceText = price.textContent.replace(',', '.');
return totalPrice += parseInt(priceText, 10);
}
function getName() {
let name = document.querySelector(`#name${currentValue}`);
nameText = name.textContent.trim();
exams.push(nameText);
return exams;
}
function displayTotal() {
let examsList = exams.join("<br>")
result.style.display = "block";
result.innerHTML =
`<span>Deu <strong>${totalPrice}</strong> conto</span>
<br><br>
<span>Exames marcados:
<br>
${examsList}</span>
`;
return result;
}
function clear() {
result.innerHTML = ''
result.style.display = "none";
currentValue = 0;
totalPrice = 0;
}
const checkboxes = document.querySelectorAll('input[type="checkbox"]');
checkboxes.forEach(checkbox => {
checkbox.addEventListener('click', getCheckboxValue);
});
calcButton.addEventListener("click", displayTotal);
clearButton.addEventListener("click", clear);