You need to do some checking before formatting the value. They are:
- Remove the currency (R$) if the user type it
- Check whether the entered value is a number or not with isNaN
See the code below:
var atual = document.querySelector('.form-control');
function sanitizeValor (valor) {
var valorSemCurrency = valor.replace(/r\$\s?/i, '');
return isNaN(valorSemCurrency) ? 0 : parseFloat(valorSemCurrency);
}
atual.addEventListener("blur", function() {
/**
* Você pode ler da seguinte forma esse if ternário
*
* If is Not a Number (isNaN) this.value então 0 caso contrário this.value
*/
var valor = sanitizeValor(this.value);
var valor2 = valor.toLocaleString("pt-br", {
style: "currency",
currency: "BRL"
});
atual.value = valor2;
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Moedas</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
</head>
<body>
<input type="text" id="form-area-imovel" class="form-control">
<script src="js/script.js"></script>
</body>
</html>
The problem with this approach is that a seemingly simple thing starts to become costly as you test "patching the code" for each situation. For example if the user type the cents with this approach they will be removed, if you want to treat this will have to remove the points and commas treat the input to see if the user has typed the currency and etc...
In this scenario I suggest you use a mask in this field that will do all this work for you and prevent the user from typing text instead of numbers.
A widely used plugin is the jQuery Mask Plugin see the example above using masks.
jQuery(document).ready(function ($) {
$('.money').mask('000.000.000.000.000,00', {reverse: true});
});
.input-group {
max-width: 500px;
margin: 20px
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.min.js"></script>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1">R$</span>
</div>
<input type="text" class="form-control money" placeholder="0,00" aria-label="Valor" aria-describedby="basic-addon1">
</div>
input type="number" does not solve your problem?
– Darlei Fernando Zillmer
In my opinion the best way would be to use a mask lib, as @Vinicius.Silva recommended.
– JDuwe