Bom dia galera, estou com um problema aqui. Preciso somar checkboxes e radio buttons para criar uma página de “estimativa de investimento” no site da minha empresa. Consigo somar/subtrair os valores dos checkboxes, contudo os radio buttons são somados sempre que clicados, e nunca são subtraídos.
Segue o código:
HTML:
`
<label>1,00 <input type="checkbox" name="ch[]" value="1,00" /></label>
<label>2,00 <input type="checkbox" name="ch[]" value="2,00" /></label>
<label>3,00 <input type="checkbox" name="ch[]" value="3,00" /></label>
<label>4,00 <input type="checkbox" name="ch[]" value="4,00" /></label>
<label>5,00 <input type="checkbox" name="ch[]" value="5,00" /></label>
<label>6,00 <input type="checkbox" name="ch[]" value="6,00" /></label>
<label>7,00 <input type="checkbox" name="ch[]" value="7,00" /></label>
<label>8,00 <input type="checkbox" name="ch[]" value="8,00" /></label>
<label>9,00 <input type="checkbox" name="ch[]" value="9,00" /></label>
<label>10,00 <input type="checkbox" name="ch[]" value="10,00" /></label>
<label>10,00 <input type="checkbox" name="ch[]" value="10,00" /></label>
<label>10,00 <input type="checkbox" name="ch[]" value="10,00" /></label>
<label>10,00 <input type="checkbox" name="ch[]" value="10,00" /></label>
<label>20,00 <input type="radio" name="ch[]" value="20,00" /></label>
<label>30,00 <input type="radio" name="ch[]" value="30,00" /></label>
<label>Resultado <input type="text" name="result" id="result" value="R$ 0,00" style="border: none; pointer-events: none; font-size: 3em;" readonly/></label>
</body>`
E agora o JS:
`String.prototype.formatMoney = function () {
var v = this;
if (v.indexOf('.') === -1) {
v = v.replace(/([\d]+)/, "$1,00");
}
v = v.replace(/([\d]+)\.([\d]{1})$/, "$1,$20");
v = v.replace(/([\d]+)\.([\d]{2})$/, "$1,$2");
v = v.replace(/([\d]+)([\d]{3}),([\d]{2})$/, "$1.$2,$3");
return v;
};
String.prototype.toFloat = function () {
var v = this;
if (!v)
return 0;
return parseFloat(v.replace(/[\D]+/g, '').replace(/([\d]+)(\d{2})$/, "$1.$2"));
};
(function () {
"use strict";
var $chs = document.querySelectorAll('input[name="ch[]"]'),
$result = document.getElementById('result'),
chsArray = Array.prototype.slice.call($chs);
chsArray.forEach(function (element, index, array) {
element.addEventListener("click", function () {
var v = this.value,
result = 0;
v = v.toFloat();
if (this.checked === true) {
result = $result.value.toFloat() + parseFloat(v);
} else {
result = $result.value.toFloat() - parseFloat(v);
}
$result.value = "R$ " + String(result).formatMoney();
});
});
}());
</script>`