HTML checkbox for Javascript

Asked

Viewed 75 times

0

Hello

I need to make a system that updates the total price as the items are being selected, but I don’t understand much Javascript, so I stuck to the following part: (HTML)

<input type="checkbox" name="porcoes[]" value="Tilápia" id="porcoes[]" onblur="calcular();">
<input type="number" name="porcoesQnt[]" style="width: 40px; text-align: center;" value="1" id="porcoesQnt[]"  onblur="calcular();">
<label for="tilapia">Tilápia</label>
<input type="number" name="porcoesVlr[]" id="porcoesVlr[]" style="text-align: center; border: none; background-color: white;" value="1.99" onblur="calcular();" readonly><br>

<input type="checkbox" name="porcoes[]" value="Camarão empanado" id="porcoes[]" onblur="calcular();">
<input type="number" name="porcoesQnt[]" style="width: 40px; text-align: center;" value="1" id="porcoesQnt[]" onblur="calcular();">
<label for="cam">Camarão empanado</label><br>
<input type="number" name="porcoesVlr[]" id="porcoesVlr[]" style="text-align: center; border: none; background-color: white;" value="1.99" onblur="calcular();" readonly><br>

<input type="checkbox" name="porcoes[]" value="Contrafilé" id="porcoes[]" onblur="calcular();">
<input type="number" name="porcoesQnt[]" style="width: 40px; text-align: center;" value="1" id="porcoesQnt[]" onblur="calcular();">>
<label for="con">Contrafilé</label><br>
<input type="number" name="porcoesVlr[]" id="porcoesVlr[]" style="text-align: center; border: none; background-color: white;" value="1.99" onblur="calcular();" readonly><br>

[...]

<div id="resultado">&nbsp;</div>

(Javascript)

function calcular() {

var i = 0;
var porcoes = document.getElementById('porcoes');
var porcoesQnt = document.getElementById('porcoesQnt');
var porcoesVlr = document.getElementById('porcoesVlr');
var total = 0;

if(porcoes != null){

  for (i = 0; i < porcoes.length; i++) {
    if(porcoes[i] != null){
        total = total + (parseInt(porcoesVlr[i].value, 10) * parseInt(porcoesQnt[i].value, 10));
    }
  }
}

document.getElementById('resultado').innerHTML = total;
}

I’ve tried everything I thought but nothing solves makes it appear updated.

1 answer

0


You don’t need id's, as Sergio said. You can select the elements by name's, but it is interesting to include each group of elements within Divs, as it will facilitate the selection of elements to perform the calculations.

See below how it looks (explanatory comments in the code):

// seleciona todos os checkbox pelo name
const cBox = document.getElementsByName("porcoes[]");
// seleciona todas as quantidades pelo name
const iQnt = document.getElementsByName("porcoesQnt[]");

// chama a função calcular() se algo for alterado
for(let i of cBox) i.onchange = calcular;
for(let i of iQnt) i.onchange = calcular;

function calcular(){
   
   const resultado = document.getElementById("resultado");
   // seleciona apenas os que estão checados
   const checados = document.querySelectorAll("[name='porcoes[]']:checked");
   
   // verifica se há pelo menos um checado
   if(checados.length){
      
      let total = 0;
      
      for(let i of checados){
         
         let wrap = i.parentNode; // seleciona a div pai
         let qnt = wrap.querySelector("[name='porcoesQnt[]']").value; // pega o valor do campo
         let vlr = wrap.querySelector("[name='porcoesVlr[]']").value; // pega o valor do campo
         
         total += qnt * vlr;
         
      }

      // insere o total com 2 casas decimais
      resultado.textContent = total.toFixed(2);
      
   }else{
      // se não tiver nenhum checado, esvazia o resultado
      resultado.textContent = "";
   }
}
<div>
   <input type="checkbox" name="porcoes[]" value="Tilápia">
   <input type="number" name="porcoesQnt[]" style="width: 40px; text-align: center;" value="1">
   <label for="tilapia">Tilápia</label>
   <input type="number" name="porcoesVlr[]" style="text-align: center; border: none; background-color: white;" value="1.99" readonly>
</div>
<div>
   <input type="checkbox" name="porcoes[]" value="Camarão empanado">
   <input type="number" name="porcoesQnt[]" style="width: 40px; text-align: center;" value="1">
   <label for="cam">Camarão empanado</label><br>
   <input type="number" name="porcoesVlr[]" style="text-align: center; border: none; background-color: white;" value="2.99" readonly><br>
</div>
<div>
   <input type="checkbox" name="porcoes[]" value="Contrafilé">
   <input type="number" name="porcoesQnt[]" style="width: 40px; text-align: center;" value="1">
   <label for="con">Contrafilé</label><br>
   <input type="number" name="porcoesVlr[]" style="text-align: center; border: none; background-color: white;" value="3.99" readonly><br>
</div>

<div id="resultado">&nbsp;</div>

  • That’s great, but you can let me know if there’s any way to update it as you change the numbers in the quantity input?

  • The code already does this, updates by checking/unchecking a checkbox or changing the quantity. test there for you to see.

  • I got. Last question, besides portions I want to do this with snacks and drinks, but how do I keep this total, because each function will have different name

  • Then you’d have to see how it goes.

  • I do a different post? Oh, and instead of div, you can send the result to an input to pull in php?

  • Have, just use . value instead of . textContent

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.