skip to Main Content

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>

2

Answers


  1. 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>
    Login or Signup to reply.
  2. The main issue with your code is due to the fact that you are not handling the deselection of checkboxes to remove values, only adding new ones when they are checked.

    You can fix the problem, simplify your code and improve its quality by changing the pattern to only calculate the totals and update the DOM when you click the ‘Calcular’ button, instead of attempting to keep a running total when the checkboxes are interacted with. To do this you can retrieve the checked checkboxes from the DOM and loop through them, as the example below shows.

    Also note that there’s a couple of additional tweaks you can make:

    • Remove the label elements. They are not being rendered at all as you’ve put them outside of the table structure, so they are redundant and can be removed.
    • Don’t use incremental id attributes. It just complicates your code and makes it harder to maintain and easier to break. Instead use common class attributes and relate content together using DOM traversal methods.
    const checkboxes = [...document.querySelectorAll('input[type="checkbox"]')];
    const calcButton = document.querySelector('#calc-button');
    const clearButton = document.querySelector('#clear-button');
    const result = document.querySelector('#result');
    
    function displayTotal() {
      let totalPrice = 0;
      let examsList = [];
      
      checkboxes.filter(cb => cb.checked).forEach(cb => {    
        const row = cb.closest('tr');
        totalPrice += parseInt(row.querySelector('.price').textContent.replace(',', '.'), 10);
        examsList.push(row.querySelector('.name').textContent);
      });
    
      result.style.display = "block";
      result.innerHTML = `<span>Deu <strong>${totalPrice}</strong> conto</span><br><br><span>Exames marcados:<br>${examsList.join('<br />')}</span>`;
      return result;
    }
    
    function clear() {
      result.innerHTML = ''
      result.style.display = "none";
      currentValue = 0;
      totalPrice = 0;
    }
    
    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>
        <td><input type="checkbox" name="check" title="check" value="1"></td>
        <td class="code">17HPC</td>
        <td class="name">17 HIDROXIPROGESTERONA</td>
        <td class="price">30,00</td>
      </tr>
      <tr>
        <td><input type="checkbox" name="check" title="check" value="2"></td>
        <td class="code">17OHC</td>
        <td class="name">17 HIDROXICORTICOIDES</td>
        <td class="price">55,00</td>
      </tr>
      <tr>
        <td><input type="checkbox" name="check" title="check" value="3"></td>
        <td class="code">17OHP</td>
        <td class="name">17 ALFA-HIDROXIPROGESTERONA</td>
        <td class="price">30,00</td>
      </tr>
      <tr>
        <td><input type="checkbox" name="check" title="check" value="4"></td>
        <td class="code">5HIAC</td>
        <td class="name">ACIDO 5 HIDROXI INDOL ACETICO</td>
        <td class="price">90,00</td>
      </tr>
      <tr>
        <td><input type="checkbox" name="check" title="check" value="5"></td>
        <td class="code">5NUC</td>
        <td class="name">5 NUCLEOTIDASE</td>
        <td class="price">130,00</td>
      </tr>
      <tr>
        <td><input type="checkbox" name="check" title="check" value="6"></td>
        <td class="code">A1A</td>
        <td class="name">ALFA 1 ANTI-TRIPSINA</td>
        <td class="price">30,00</td>
      </tr>
      <tr>
        <td><input type="checkbox" name="check" title="check" value="7"></td>
        <td class="code">A1AF</td>
        <td class="name">ALFA 1 ANTI-TRIPSINA FECAL</td>
        <td class="price">80,00</td>
      </tr>
      <tr>
        <td><input type="checkbox" name="check" title="check" value="8"></td>
        <td class="code">AACH1</td>
        <td class="name">TESTE RAPIDO CHIKUNGUNYA IGG/IGM</td>
        <td class="price">125,00</td>
      </tr>
      <tr>
        <td><input type="checkbox" name="check" title="check" value="9"></td>
        <td class="code">AACHI</td>
        <td class="name">ANTICORPOS ANTI CHIKUNGUNYA IGG/IGM</td>
        <td class="price">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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search