-2
I have a summation system using checkbox
and radio button
always used it and it always worked, but I tried to put it on another page I have and it stopped working the code is this one:
function formatCurrency(num) { // função original - sem modificação
num = num.toString().replace(/\$|\,/g, '');
if (isNaN(num)) num = "0";
cents = Math.floor((num * 100 + 0.5) % 100);
num = Math.floor((num * 100 + 0.5) / 100).toString();
if (cents < 10) cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
return ("" + num + "." + cents);
}
var form = document.forms[0];
var inputs = form.querySelectorAll('input[type=checkbox],input[type=radio]');
// iterar todos os inputs
for (var i = 0; i < inputs.length; i++) {
// vincular função ao evento "change"
inputs[i].addEventListener('change', function() {
var soma = 0;
for (var j = 0; j < inputs.length; j++) {
if (inputs[j].checked) {
// interpreta como float, usando parseFloat ao invés de eval
soma += parseFloat(inputs[j].value);
}
}
form.hiddentotal.value = soma; // atribui valor ao campo oculto
form.total.value = formatCurrency(soma) // exibe valor formatado
}, false);
}
label {
display: inline-block;
width: 210px;
float: left;
}
<form name="myform">
<label><input type="radio" name="tamanho" value="9.25">250GR</label>
<label><input type="radio" name="tamanho" value="11.25">400GR</label>
<label><input type="radio" name="tamanho" value="14.25">600GR</label>
<label><input type="checkbox" name="valor" value="2">L. Ninho</label>
<label><input type="checkbox" name="valor" value="3">Nutella</label>
<label><input type="checkbox" name="valor" value="3">Chantilly</label>
<label><input type="checkbox" name="valor" value="1.5">L. Condensado</label>
<label><input type="checkbox" name="valor" value="1.5">S. Valsa</label>
<label><input type="checkbox" name="valor" value="2.5">Sorvete</label>
<div>
<span>Valor Total:</span>
<input name="total" type="text" readonly disabled>
<input type="hidden" name="hiddentotal" value="0">
</div>
</form>
Here by the snippet it works normal, but when I put on the site it does not work.
What happens when you try to use it on your page? Shows error? Have any messages in the browser console?
– Pedro Camara Junior
It’s very likely to be a conflict, could you post the rest of the page code ? take a look if these selectors are already running another task.
– Gabriel Rodrigues
See in Chrome’s Inspect Element or another browser if there is a script error.
– Diego Souza
Look at this example in Jsfiddle. Want me to adapt to a radio button and checkbox version? Or you can from there?
– Ivan Ferrer
Try to be more specific and put less code that so we can’t even edit the question. The question is being discussed at the finish line for that very reason: When editing the question you have more than 30000 characters allowed
– Jorge B.