replace Javascript function is not working

Asked

Viewed 316 times

1

I have a function in a part of the system that is not working. Error appears Uncaught TypeError: addPriceAddProd.replace is not a function but I don’t know what I’m doing wrong. Could anyone help me? Follow my code that does the action.

function subtrairMenos1Add<?=$idIngredientAdicional?>() {
var n1 = parseInt(document.getElementById('qtdIngredientAdicional<?=$idIngredientAdicional?>').value);
var n2 = parseInt(1);
                                                            document.getElementById('qtdIngredientAdicional<?=$idIngredientAdicional?>').value = n1 - 1;
valorInputGeneral = document.getElementById('qtdIngredientAdicional<?=$idIngredientAdicional?>').value;
orgPriceProd = document.getElementById("orgPriceProd").value;
if(valorInputGeneral < 1) {
                                                                document.getElementById('qtdIngredientAdicional<?=$idIngredientAdicional?>').value = 0;
}
if(valorInputGeneral > 0){
                                                            //if(valorInputGeneral > 0){
var priceAdicional = document.getElementById("adicionalPrice<?=$idIngredientAdicional?>").value;
                                                            //alert(priceAdicional);
var priceProd = document.getElementById("priceProd").value;
var priceProdFormatAm = priceProd.replace(",",".");

var addPriceAddProd = parseFloat(priceProdFormatAm) - parseFloat(priceAdicional);
                                                            //alert(addPriceAddProd);
//var priceProdFormatBr = addPriceAddProd.replace(".",",");
 var addPriceAddProdBr = addPriceAddProd.replace(".",",");
                                                            alert(addPriceAddProdBr);
                                                            document.getElementById("priceProd").value = addPriceAddProd;
 //}
}

if(valorInputGeneral <= 0){
                                                                document.getElementById("priceProd").value = orgPriceProd;
   }
}

1 answer

6


The result of parseFloat is a Number, and the method .replace is a String method. To do this replace you have to convert the number back to String.

But maybe that’s not what you want to do... if that’s it then the question is answered. If what you want is to format the number at the end, you can use the .toLocaleString() that converts numbers to String with the format of the country you pass. For example:

const valor = 2354.56;
const representacao = valor.toLocaleString('pt-BR');
console.log(representacao); // 2.354,56

  • 1

    Thank you very much!! solved my problem

Browser other questions tagged

You are not signed in. Login or sign up in order to post.