Return of strings in thousands of separators Javascript [duplicated]

1

I have this little script that will place thousands separators in an html input.

The problem is presented in mobile, when returns the separated numbers, return the complete chain, that is to say I put 10000 and it returns 10.1000

var separador = document.getElementById('separadorMiles');

separador.addEventListener('keyup', (e) => {
    var entrada = e.target.value.split('.').join('');
    entrada = entrada.split('').reverse();
    
    var salida = [];
    var aux = '';
    
    var paginador = Math.ceil(entrada.length / 3);
    
    for(let i = 0; i < paginador; i++) {
        for(let j = 0; j < 3; j++) {
            "123 4"
            if(entrada[j + (i*3)] != undefined) {
                aux += entrada[j + (i*3)];
            }
        }
        salida.push(aux);
        aux = '';
       
        e.target.value = salida.join('.').split("").reverse().join('');
    }
}, false);
<!doctype html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8" lang=""> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9" lang=""> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang=""> <!--<![endif]-->
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="apple-touch-icon" href="apple-touch-icon.png">

        <link rel="stylesheet" href="css/bootstrap.min.css">
        <link rel="stylesheet" href="css/bootstrap-theme.min.css">
        <link rel="stylesheet" href="css/main.css">
        
        <script src="js/vendor/modernizr-2.8.3-respond-1.4.2.min.js"></script>

        <script type="text/javascript" src="/path/to/jquery.js"></script>



         <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/3.1.3/css/bootstrap-datetimepicker.min.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.3/css/bootstrapValidator.min.css">
        <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.3/js/bootstrapValidator.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.2/moment.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/3.1.3/js/bootstrap-datetimepicker.min.js"></script>
        <link rel="stylesheet" href="css/style.css">
        
    </head>
    <body>
        <!--[if lt IE 8]>
            <p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
        <![endif]-->
<div class="container presentacion">
Este simulador ayuda a visualizar el resultado obtenido por una inversión en fechas pasadas, utilizando datos reales del Fondo de inversión
</div>
<br>
<div class="row">
<div class="container">
    
        <form action="" id="form">
        <div class="col-xs-5 col-sm-5 col-md-5 col-lg-5">
            <div class="form-group">
            <label for="male">Monto a ingresar</label><br>
            <input type="text" name="inversion" placeholder="$10.000.000" class="form-control" id="separadorMiles" required><br>
            <label for="startDate">Fecha Inicio</label><br>
            <input type="date" name="date" id="dateIni"  value="2018-02-08" min="2016-04-27" max="2018-03-07" class="form-control"><br>
            <label for="endDate">Fecha Terminación</label><br>
            <input type="date" name="date" id="dateFin"  value="2018-03-08" min="2016-04-28" max="2018-03-08"  class="form-control"><br>
            <br>
            <button type="button" onclick="getData()" class="btn btn-default">Consultar</button>
            <script type="text/javascript" src="js/app-60.js?53"></script>
            </div>
        </div
>        <div class="col-xs-7 col-sm-7 col-md-7 col-lg-7">
            <div class="centrar-vertical">
            
            
                
            <div class="box-max">
                <div class="box-one"><output id="salidainversion" >Inversión</output></div>
                <div class="box-two"><output id="salidaGanancias" >Ganancias</output></div>
                <svg height="120" width="200">
                    <line x1="50" y1="115" x2="130" y2="45" style="stroke:rgb(244,193,0);stroke-width:2" />
                    <circle cx="50" cy="115" r="3" style="stroke:rgb(244,193,0);stroke-width:5"/>
                    <circle cx="130" cy="45" r="3" style="stroke:rgb(244,193,0);stroke-width:5"/>
                </svg>
            </div>
            <div class="box-min">
                <div class="box-tre"><output id="salidadateIni" >01-10-2017</output> </div>
                <div class="box-four"><output id="salidadateFin" >31-10-2017</output> </div>
            </div>

        </div>
    </div>

        </form> 
    
</div>
</div>
<div class="row">
<div class="container">
<p class="advertencia">&nbsp;&nbsp; *Los rendimientos pasados, no garantizan rendimientos futuros</p>
</div>
</div>

        <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.2.min.js"><\/script>')</script>
            <script src="./js/index.js"></script>
            <script src="./js/jquery-3.2.1.min.js"></script>
            <script src="./js/tether.min.js"></script>
            <script src="./js/popper.min.js"></script>
        <script src="./js/bootstrap.min.js"></script>
        <script src="js/vendor/bootstrap.min.js"></script>
        <script src="js/main.js"></script>
    </body>
</html>
    
asked by Elliot Frank 09.03.2018 в 21:08
source

2 answers

1

Try to subscribe to the input event instead of keyup . I take this opportunity to suggest a " simpler " way to achieve the same result.

Solution:

var separador = document.getElementById('separadorMiles');

separador.addEventListener('input', (e) => {
    var entrada = e.target.value.split(','),
      parteEntera = entrada[0].replace(/\./g, ''),
      parteDecimal = entrada[1],
      salida = parteEntera.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1.");
      
    e.target.value = salida + (parteDecimal !== undefined ? ',' + parteDecimal : '');
}, false);
<input type="text" name="inversion" placeholder="$10.000.000" class="form-control" id="separadorMiles" required><br>

Reference:

answered by 09.03.2018 в 21:51
1

As I mentioned in my answer to another similar question,

  

Today, most modern browsers support Intl.NumberFormat which helps us to format a number without having to resort to regular expressions or specific jQuery functions.

In the previous league, compatibility with desktop, mobile and server browsers is included at the bottom of the page.

Below is the example that I included in the aforementioned answer, adapted to show the Argentine peso format, that is, $ sign, period as thousands separator as decimal separator.

var numero = 1E6 + 56 / 100; //Un millón y 56 centésimas
document
  .getElementById('salida')
  .innerHTML = new Intl.NumberFormat('es-AR', {
    style: 'currency',
    currency: 'ARS'
  }).format(numero);
<div id="salida"></div>

In the following example I tried to apply the above to allow an input to automatically add the thousands separator and allow the inclusion of decimals but is incomplete because it needs to consider several cases like the one that the user changes the text insertion point or you want to write a penny (0.01).

var monto = document.querySelector('input');
var options = {
	style:'currency',
  currency:'ARS',
  minimumFractionDigits:0
};
monto.addEventListener('input',function(){
  // Si el último caracter es una coma, deberemos agregarla
  var separador = (this.value.substr(this.value.length - 1,1)===',')?',':''; 
	var monto1 = this.value
  .replace(/[^\d,]/g,"") //remover $ punto y otros caracteres no validos
  .replace(",","."); // JavaScript usa punto como separador decimal para los números,entonces reemplazamos la coma por un punto
  this.value = Intl.NumberFormat('es-AR',options).format(monto1)
  + separador; // Si el último caracter es una coma, agregarlo.
});
<input type="text" placeholder="$ 10.000">

The solution is most likely to be to adopt a library to mask an entry that includes the desired currency format or to customize it.

Related questions

answered by 09.03.2018 в 22:24