Problem in converting the input values into Real, example: R$ 20,00

Asked

Viewed 751 times

-1

I created a Script to format Input values for Real Currencies, but there is a problem, when you put text, display "Nan", I need that can only type number and not text.

var atual = document.querySelector('.form-control');
atual.addEventListener("blur", function() {
  var valor = parseInt(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>

  • input type="number" does not solve your problem?

  • In my opinion the best way would be to use a mask lib, as @Vinicius.Silva recommended.

2 answers

3

You need to do some checking before formatting the value. They are:

  1. Remove the currency (R$) if the user type it
  2. 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>

0

See if that helps you.

<script type="text/javascript">
  function mascara(o,f){
    v_obj=o
    v_fun=f
    setTimeout("execmascara()",1)
}
function execmascara(){
    v_obj.value=v_fun(v_obj.value)
}

function mnum(v){
    v=v.replace(/\D/g,"");                                      //Remove tudo o que não é dígito
    return v;
}

function id( el ){
    return document.getElementById( el );
}

function next( el, next )
{
    if( el.value.length >= el.maxLength ) 
        id( next ).focus(); 
}
</script>

<input type="text" class="form-control" id="valor" name="valor" placeholder="" onkeypress="mascara(this, mvalor);"> 

Browser other questions tagged

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