activate JS function when it brings established value

2

I have a page to update where it brings me the data according to the record that I have selected, I have numerical fields I've validated them with a separation function of thousands and decimals, but in what method should I place the function so that when loading the numbers automatically I formatted the value without having to focus, focusOut, keypress or keyup

function formatearNumero(nStr) {
    nStr += '';
    x = nStr.split(',');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}
<input id="txtValor">
    
asked by Ivxn 03.10.2018 в 19:31
source

1 answer

0

The idea would be after your ajax go through each record and invoke each of the quantities and pass them to the formatearNumero() function like this:

This is an example for you to guide yourself

const cifras = [100,1000,2050.60];

function formatearNumero(nStr) {
    nStr += '';
    x = nStr.split(',');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

cifras.forEach(function(cifra) {
  console.log(formatearNumero(cifra));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Now if you already have the amounts in the inputs you can do this:

function formatearNumero(nStr) {
    nStr += '';
    x = nStr.split(',');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

alert("Los campos aun no estan formateados, una vez que le des aceptar en el alert se formatearan")

$(".cifra").each(function(){
  var valorFormateado = formatearNumero($(this).val());
  $(this).val(valorFormateado);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table>
  <tr>
    <td>
      <input type="text" class="cifra" value="100">
    </td>
  </tr>
  <tr>
    <td>
      <input type="text" class="cifra" value="1000">
    </td>
  </tr>
  <tr>
    <td>
      <input type="text" class="cifra" value="2050.60">
    </td>
  </tr>
</table>
    
answered by 03.10.2018 / 20:22
source