JavaScript function not working correctly

1

Good afternoon, I have the function below javascript to hold the account when you leave the discount field:

function calcular1() {
  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;
  };
  var v1 = document.getElementById("txtValoraPagar").value;
  var v2 = document.getElementById("txtDesconto").value;
  var txtTotalPagar = document.getElementById("txtTotalPagar");
  if ((v2.replace("R$", "").replace(",", ".").replace(/\s*/g, '')) > (v1.replace(",", ".").replace(/\s*/g, ''))) {
    alert('Valor do desconto não pode ser maior do que o valor a receber.');
    document.getElementById("txtDesconto").value = '';
    return false;
  }
  if ((v1 != "") && (v2 != "") && (v1.replace(",", ".").replace(/\s*/g, '') >= v2.replace("R$", "").replace(",", ".").replace(/\s*/g, ''))) {
    txtTotalPagar.value = (eval(v1.replace(",", ".") - eval(v2.replace("R$", "").replace(",", "."))));
    txtTotalPagar.value = 'R$ ' + String(txtTotalPagar.value).formatMoney();
  }

For example, if the value is 15.00 and the discount is 5.00 it goes in as if the discount was greater than the value, and it informs the alert. Now if the value is 15.00 and I place the discount of 1.00, it works, and shows the total amount to pay right, of 14.00. By what oq to understand, he is doing the count of the first number of 15, q is 1, and picks up 5. I do not know why this is occurring.

    
asked by anonymous 13.12.2017 / 16:34

1 answer

1

You have to compare numbers instead of characters.

Just one more thing, put the names of your most intuitive variables. Can not have variable named v1, v2. What do they mean? Clearer variables with name 'value' and 'discount' are what they really represent.

function calcular2() {
   var txtValor = document.getElementById("txtValoraPagar").value;
   var txtDesconto = document.getElementById("txtDesconto").value;
   var txtTotalPagar = document.getElementById("txtTotalPagar");
   var valor =0;
   var desconto =0; 
   if(txtValor != null)
     valor = Number(txtValor.replace(/[R\$ ]/g, '').replace(',', '.'));
   if(txtDesconto != null)
     desconto = Number(txtDesconto.replace(/[R\$ ]/g, '').replace(',', '.'));
   if(desconto > valor){
     alert('Valor do desconto não pode ser maior do que o valor a receber.');
     return false;
   }else if (valor >= desconto){
   	 txtTotalPagar.value = 'R$ ' + (valor - desconto);
   } 
}
Valor: <input type="text" id="txtValoraPagar" value="R$ ">
<br>
Desconto: <input type="text" id="txtDesconto" value="R$ ">
<br>
Total: <input type="text" id="txtTotalPagar" readonly="true" placeholder="Valor final">
<br>
<button onclick="calcular2()">Calcular</button>
    
13.12.2017 / 17:49