The error is on the line
sum + = parseInt (inputs [i] .value);
The label
element does not have the value
attribute, the way you are expecting.
For this, you need to get the text of label
, which by DOM
, is your first child.
So:
soma += parseFloat(inputs[i].firstChild.nodeValue.substr(3).replace(/\./g, "").replace(/,/g, ".")));
- The
substr
is to skip the beginning of your string "R$ "
- I used
parseFloat
because of decimal places
- The
replace
is to remove the thousand separator (% with%) and then replace the decimal separator "."
with ","
, so "."
can work correctly
Furthermore, after reading the fiddle completely, there was an error in the currency conversion function: it was missing to replace the parseFloat
generated by the "."
method with toFixed
, in addition to correcting the regular expression that adds the thousand separator. The full fiddle is here .
The final corrected code of the function in question is shown below:
function formatDinheiro(n, currency) {
//às vezes n vem como NaN, quando o usuário deixa o campo em branco
if (isNaN(n))
n = 0;
//converte n para string com 2 casas decimais
var x = (currency + " " + n.toFixed(2).replace(/\./g, ",")).split(","),
x1 = x[0],
x2 = ((x.length > 1) ? "," + x[1] : ""),
rgx = /(\d+)(\d{3})/;
//acrescenta um separador de milhar a cada 3 dígitos
while (rgx.test(x1))
x1 = x1.replace(rgx, '$1' + '.' + '$2');
return x1 + x2;
}
Another error is that when doing:
var inputs = id ('Products'). getElementsByTagName ('label');
The ","
with subtotal is also returned in the array, so its value entered the sum again. The corrected code for this function is shown below:
function somaLabelProduto() {
var inputs = id("Produto").getElementsByTagName('label');
var soma = 0;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].id != "sub_total_0")
soma += parseFloat(inputs[i].firstChild.nodeValue.substr(3).replace(/\./g, "").replace(/,/g, "."));
}
document.getElementById('sub_total_0').innerHTML = formatDinheiro(soma, "R$");
}