Search code examples
javascripthtmlcheckboxoutputlogic

When I select the checkbox, it displays its value just fine. When I de-select it, it continues to display


enter image description here

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".

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);
<style>
  @import url('https://fonts.googleapis.com/css2?family=Michroma&display=swap');
</style>
<h1>Calculadora da Duda</h1>

<table border="1">
  <tr>
    <th>Check</th>
    <th>Código</th>
    <th>Nome</th>
    <th>Preço</th>
  </tr>

  <tr>
    <label for="checkbox1"></label>
    <td><input type="checkbox" name="check" title="check" value="1"></td>
    <td id="code1">17HPC</td>
    <td id="name1">17 HIDROXIPROGESTERONA</td>
    <td id="price1">30,00</td>
  </tr>

  <tr>
    <label for="checkbox2"></label>
    <td><input type="checkbox" name="check" title="check" value="2"></td>
    <td id="code2">17OHC</td>
    <td id="name2">17 HIDROXICORTICOIDES</td>
    <td id="price2">55,00</td>
  </tr>

  <tr>
    <label for="checkbox3"></label>
    <td><input type="checkbox" name="check" title="check" value="3"></td>
    <td id="code3">17OHP</td>
    <td id="name3">17 ALFA-HIDROXIPROGESTERONA</td>
    <td id="price3">30,00</td>
  </tr>

  <tr>
    <label for="checkbox4"></label>
    <td><input type="checkbox" name="check" title="check" value="4"></td>
    <td id="code4">5HIAC</td>
    <td id="name4">ACIDO 5 HIDROXI INDOL ACETICO</td>
    <td id="price4">90,00</td>
  </tr>

  <tr>
    <label for="checkbox5"></label>
    <td><input type="checkbox" name="check" title="check" value="5"></td>
    <td id="code5">5NUC</td>
    <td id="name5">5 NUCLEOTIDASE</td>
    <td id="price5">130,00</td>
  </tr>

  <tr>
    <label for="checkbox6"></label>
    <td><input type="checkbox" name="check" title="check" value="6"></td>
    <td id="code6">A1A</td>
    <td id="name6">ALFA 1 ANTI-TRIPSINA</td>
    <td id="price6">30,00</td>
  </tr>

  <tr>
    <label for="checkbox7"></label>
    <td><input type="checkbox" name="check" title="check" value="7"></td>
    <td id="code7">A1AF</td>
    <td id="name7">ALFA 1 ANTI-TRIPSINA FECAL</td>
    <td id="price7">80,00</td>
  </tr>

  <tr>
    <label for="checkbox8"></label>
    <td><input type="checkbox" name="check" title="check" value="8"></td>
    <td id="code8">AACH1</td>
    <td id="name8">TESTE RAPIDO CHIKUNGUNYA IGG/IGM</td>
    <td id="price8">125,00</td>
  </tr>

  <tr>
    <label for="checkbox9"></label>
    <td><input type="checkbox" name="check" title="check" value="9"></td>
    <td id="code9">AACHI</td>
    <td id="name9">ANTICORPOS ANTI CHIKUNGUNYA IGG/IGM</td>
    <td id="price9">240,00</td>
  </tr>

</table>

<div id="final-buttons">
  <button type="button" id="calc-button">Calcular</button>
  <button type="button" id="clear-button">Limpar</button>
</div>

<div id="result"></div>


Solution

  • It seems that your issue is about an unset checked checkbox that does not affect the total and the exams. You should, in case of unchecking, remove this amount from the total price and the name of the exam from the exams variable.

    The following will describe how should you modify your code to get it right:

    • GetCheckboxValue should be adjusted for both check and uncheck:
    • Modify the getPrice and getName to update values when removed if unchecked.
    • Modify the displayTotal function to accurately portray these changes.
      const calcButton = document.getElementById('calc-button');
      const clearButton = document.getElementById('clear-button');
      const result = document.getElementById('result');
      
      let totalPrice = 0;
      let exams = [];
      
      function getCheckboxValue(event) {
        const checkboxValue = event.target.value;
        if (event.target.checked) {
          currentValue = checkboxValue;
          addPrice(currentValue);
          addName(currentValue);
        } else {
          removePrice(checkboxValue);
          removeName(checkboxValue);
        }
      }
      
      function addPrice(value) {
        let price = document.querySelector(`#price${value}`);
        let priceText = price.textContent.replace(',', '.');
        totalPrice += parseInt(priceText, 10);
      }
      
      function removePrice(value) {
        let price = document.querySelector(`#price${value}`);
        let priceText = price.textContent.replace(',', '.');
        totalPrice -= parseInt(priceText, 10);
      }
      
      function addName(value) {
        let name = document.querySelector(`#name${value}`);
        let nameText = name.textContent.trim();
        exams.push(nameText);
      }
      
      function removeName(value) {
        let name = document.querySelector(`#name${value}`);
        let nameText = name.textContent.trim();
        exams = exams.filter(exam => exam !== nameText);
      }
      
      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>
        `;
      }
      
      function clear() {
        result.innerHTML = ''
        result.style.display = "none";
        currentValue = 0;
        totalPrice = 0;
        exams = [];
        // Uncheck all checkboxes
        document.querySelectorAll('input[type="checkbox"]').forEach(checkbox => checkbox.checked = false);
      }
      
      const checkboxes = document.querySelectorAll('input[type="checkbox"]');
      checkboxes.forEach(checkbox => {
        checkbox.addEventListener('click', getCheckboxValue);
      });
      
      calcButton.addEventListener("click", displayTotal);
      clearButton.addEventListener("click", clear);
      <style>
        @import url('https://fonts.googleapis.com/css2?family=Michroma&display=swap');
      </style>
      <h1>Calculadora da Duda</h1>
      
      <table border="1">
        <tr>
          <th>Check</th>
          <th>Código</th>
          <th>Nome</th>
          <th>Preço</th>
        </tr>
      
        <tr>
          <label for="checkbox1"></label>
          <td><input type="checkbox" name="check" title="check" value="1"></td>
          <td id="code1">17HPC</td>
          <td id="name1">17 HIDROXIPROGESTERONA</td>
          <td id="price1">30,00</td>
        </tr>
      
        <tr>
          <label for="checkbox2"></label>
          <td><input type="checkbox" name="check" title="check" value="2"></td>
          <td id="code2">17OHC</td>
          <td id="name2">17 HIDROXICORTICOIDES</td>
          <td id="price2">55,00</td>
        </tr>
      
        <tr>
          <label for="checkbox3"></label>
          <td><input type="checkbox" name="check" title="check" value="3"></td>
          <td id="code3">17OHP</td>
          <td id="name3">17 ALFA-HIDROXIPROGESTERONA</td>
          <td id="price3">30,00</td>
        </tr>
      
        <tr>
          <label for="checkbox4"></label>
          <td><input type="checkbox" name="check" title="check" value="4"></td>
          <td id="code4">5HIAC</td>
          <td id="name4">ACIDO 5 HIDROXI INDOL ACETICO</td>
          <td id="price4">90,00</td>
        </tr>
      
        <tr>
          <label for="checkbox5"></label>
          <td><input type="checkbox" name="check" title="check" value="5"></td>
          <td id="code5">5NUC</td>
          <td id="name5">5 NUCLEOTIDASE</td>
          <td id="price5">130,00</td>
        </tr>
      
        <tr>
          <label for="checkbox6"></label>
          <td><input type="checkbox" name="check" title="check" value="6"></td>
          <td id="code6">A1A</td>
          <td id="name6">ALFA 1 ANTI-TRIPSINA</td>
          <td id="price6">30,00</td>
        </tr>
      
        <tr>
          <label for="checkbox7"></label>
          <td><input type="checkbox" name="check" title="check" value="7"></td>
          <td id="code7">A1AF</td>
          <td id="name7">ALFA 1 ANTI-TRIPSINA FECAL</td>
          <td id="price7">80,00</td>
        </tr>
      
        <tr>
          <label for="checkbox8"></label>
          <td><input type="checkbox" name="check" title="check" value="8"></td>
          <td id="code8">AACH1</td>
          <td id="name8">TESTE RAPIDO CHIKUNGUNYA IGG/IGM</td>
          <td id="price8">125,00</td>
        </tr>
      
        <tr>
          <label for="checkbox9"></label>
          <td><input type="checkbox" name="check" title="check" value="9"></td>
          <td id="code9">AACHI</td>
          <td id="name9">ANTICORPOS ANTI CHIKUNGUNYA IGG/IGM</td>
          <td id="price9">240,00</td>
        </tr>
      
      </table>
      
      <div id="final-buttons">
        <button type="button" id="calc-button">Calcular</button>
        <button type="button" id="clear-button">Limpar</button>
      </div>
      
      <div id="result"></div>