[Resolvido] PHP - Erro com multiplicação de campos
Caros amigos.
Tenho 2 campos:
qtde ===> campo inteiro
vrUnit ==> campo moeda
Preciso fazer a multiplicação na tela, para mostrar ao usuário.
Estou com o seguinte código:
function calcular(){
var valor1 = parseInt(document.getElementById('qtde').value, 10);
var valor2 = parseInt(document.getElementById('vrUnit').value, 10);
document.getElementById('vrTotal').value = valor1 * valor2;
}
O código acima faz a multiplicação. O que não acontece que preciso, seria formatar o campo **vrUnit**, para máscara moeda.
Utilizei o código abaixo:
//Valida os campos moeda do formulário
function dinheiro(cur,len) {
n='__0123456789';
d=cur.value;
l=d.length;
r='';
if (l > 0){
z=d.substr(0,l-1);
s='';
a=2;
for (i=0; i < l; i++){
c=d.charAt(i);
if (n.indexOf(c) > a){
a=1;
s+=c;
};
};
l=s.length;
t=len-1;
if (l > t){
l=t;
s=s.substr(0,t);
};
if (l > 2){
r=s.substr(0,l-2)+','+s.substr(l-2,2);
} else {
if (l == 2){
r='0,'+s;
} else {
if (l == 1){
r='0,0'+s;
};
};
};
if (r=='0,00'){
return false;
} else {
l=r.length;
if (l > 6){
j=l%3;
w=r.substr(0,j);
wa=r.substr(j,l-j-6);
wb=r.substr(l-6,6);
if (j > 0){
w+='.';
};
k=(l-j)/3-2;
for (i=0; i < k; i++){
w+=wa.substr(i*3,3)+'.';
};
r=w+wb;
};
};
};
if (r.length <= len){
cur.value=r;
} else {
cur.value=z;
};
return 'ok';
};
function id(el) {
return document.getElementById( el );
}
function total( qtde, vrUnit ) {
return parseFloat(qtde.replace(',', '.'), 10) * parseFloat(vrUnit.replace(',', '.'), 10);
}
window.onload = function() {
id('vrUnit').addEventListener('keyup', function() {
var result = total( this.value , id('qtde').value );
id('vrTotal').value = String(result.toFixed(2)).formatMoney();
});
id('qtde').addEventListener('keyup', function(){
var result = total( id('vrTotal').value , this.value );
id('vrTotal').value = String(result.toFixed(2)).formatMoney();
});
}
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;
};
Até faz a multiplicação, mas quando digito o valor: 1.234.567,89, com o código acima após digitar o valor unitário, apenas mostra: 123,60.
Não entendo o porque.Discussão (1)
Carregando comentários...