maxlength in currency mask

2

I'm using this currency mask, it works fine even though putting a maxlength into input does not limit the number of numbers.

<script language="javascript">
function MascaraMoeda(objTextBox, SeparadorMilesimo, SeparadorDecimal, e){
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode = (window.Event) ? e.which : e.keyCode;
    if (whichCode == 13 || whichCode == 8) return true;
    key = String.fromCharCode(whichCode); // Valor para o código da Chave
    if (strCheck.indexOf(key) == -1) return false; // Chave inválida
    len = objTextBox.value.length;
    for(i = 0; i < len; i++)
        if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
    aux = '';
    for(; i < len; i++)
        if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) objTextBox.value = '';
    if (len == 1) objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
    if (len == 2) objTextBox.value = '0'+ SeparadorDecimal + aux;
    if (len > 2) {
        aux2 = '';
        for (j = 0, i = len - 3; i >= 0; i--) {
            if (j == 3) {
                aux2 += SeparadorMilesimo;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        objTextBox.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
        objTextBox.value += aux2.charAt(i);
        objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
    }
    return false;
}
</script>
<input type="text" name="post_price" required="required" class="form-control form-control-md" maxlength="8" onKeyPress="return(MascaraMoeda(this,'.',',',event))" placeholder="<?php esc_html_e('Sale price', 'classiera') ?>">

One more thing (it does not bother much, but I find it annoying), tab does not work when I'm in this field.

    
asked by anonymous 06.12.2017 / 20:59

4 answers

1

Change the if (len > 2) { to if (len > 2 && len < 7) { .

  

% w / o% means that it is only allowed to enter up to 6 numbers,   summing up with the 2 decimal and thousand character separator characters that are   added automatically, totaling 8 characters.

function MascaraMoeda(objTextBox, SeparadorMilesimo, SeparadorDecimal, e){
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode = (window.Event) ? e.which : e.keyCode;
    if (whichCode == 13 || whichCode == 8) return true;
    key = String.fromCharCode(whichCode); // Valor para o código da Chave
    if (strCheck.indexOf(key) == -1) return false; // Chave inválida
    len = objTextBox.value.length;
    for(i = 0; i < len; i++)
        if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
    aux = '';
    for(; i < len; i++)
        if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) objTextBox.value = '';
    if (len == 1) objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
    if (len == 2) objTextBox.value = '0'+ SeparadorDecimal + aux;
    if (len > 2 && len < 7) {
  
        aux2 = '';
        for (j = 0, i = len - 3; i >= 0; i--) {
            if (j == 3) {
                aux2 += SeparadorMilesimo;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        objTextBox.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
        objTextBox.value += aux2.charAt(i);
        objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
    }
    return false;
}
<input type="text" name="post_price" required="required" class="form-control form-control-md" maxlength="8" onKeyPress="return(MascaraMoeda(this,'.',',',event))" placeholder="<?php esc_html_e('Sale price', 'classiera') ?>">
  

One more thing (it does not get in the way, but I find it annoying), the tab   does not work when I'm in this field.

In the example above, the tab works perfectly. This information lacks further details for resolution. Please post the comments below for more information on the issue so we can resolve it.

    
06.12.2017 / 22:47
0

Modifications

//recupera o valor de maxLength
var maxLength = document.getElementById("meuInput").maxLength;
//como há adição de 2 caracteres automaticamente
//temos que só se pode digitar o valor de maxLength subtraído de 2
var permitido = maxLength-1;
if (len > 2 && len < permitido) {
  

This way if you change the value of maxLength in the input the round wheel script without needing to change any variable or condition

    

function MascaraMoeda(objTextBox, SeparadorMilesimo, SeparadorDecimal, e){
var sep = 0;
var key = '';
var i = j = 0;
var len = len2 = 0;
var strCheck = '0123456789';
var aux = aux2 = '';
var whichCode = (window.Event) ? e.which : e.keyCode;
if (whichCode == 13 || whichCode == 8) return true;
key = String.fromCharCode(whichCode); // Valor para o código da Chave
if (strCheck.indexOf(key) == -1) return false; // Chave inválida
len = objTextBox.value.length;
for(i = 0; i < len; i++)
    if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
aux = '';
for(; i < len; i++)
    if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i);
aux += key;
len = aux.length;
if (len == 0) objTextBox.value = '';
if (len == 1) objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
if (len == 2) objTextBox.value = '0'+ SeparadorDecimal + aux;
//recupera o valor de maxLength
var maxLength = document.getElementById("meuInput").maxLength;
//como há adição de 2 caracteres automaticamente
//temos que só se pode digitar o valor de maxLength subtraído de 2
var permitido = maxLength-1;
if (len > 2 && len < permitido) {

    aux2 = '';
    for (j = 0, i = len - 3; i >= 0; i--) {
        if (j == 3) {
            aux2 += SeparadorMilesimo;
            j = 0;
        }
        aux2 += aux.charAt(i);
        j++;
    }
    objTextBox.value = '';
    len2 = aux2.length;
    for (i = len2 - 1; i >= 0; i--)
    objTextBox.value += aux2.charAt(i);
    objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
}
return false;
}
<input id="meuInput" type="text" name="post_price" required="required" class="form-control form-control-md" maxlength="8" onKeyPress="return(MascaraMoeda(this,'.',',',event))" placeholder="<?php esc_html_e('Sale price', 'classiera') ?>">
    
07.12.2017 / 04:12
0

This function works perfectly:

<script>
//Chamar essa função na tag imput: onkeyup="moeda(this);"
function moeda(z){
    v = z.value;
    v=v.replace(/\D/g,"") // permite digitar apenas numero
    v=v.replace(/(\d{1})(\d{14})$/,"$1.$2") // coloca ponto antes dos ultimos digitos
    v=v.replace(/(\d{1})(\d{11})$/,"$1.$2") // coloca ponto antes dos ultimos 11 digitos
    v=v.replace(/(\d{1})(\d{8})$/,"$1.$2") // coloca ponto antes dos ultimos 8 digitos
    v=v.replace(/(\d{1})(\d{5})$/,"$1.$2") // coloca ponto antes dos ultimos 5 digitos
    v=v.replace(/(\d{1})(\d{1,2})$/,"$1,$2") // coloca virgula antes dos ultimos 2 digitos
    z.value = v;
}
</script>

And INPUT :

<input type="text" onkeyup="moeda(this);" maxlength="9">
    
07.12.2017 / 22:29
0

At the end of this code, I can do it with regex, I think it's still better to improve, and you can understand it because it has everything in small functions.

const currencyInput = document.querySelectorAll('.input-currency');

currencyInput.forEach(input => input.addEventListener('keyup', _ => currencyFormat(input)));

function currencyFormat(input) {  
  let newValue = input.value.replace(/\D/g, '');
  
  newValue = addLeftZero(newValue);
  newValue = removeLeftZero(newValue);
  newValue = addDecimalSeparator(newValue);
  newValue = addThousandSeparator(newValue);
  
  input.value = newValue;
  
  function addDecimalSeparator(value) {
    return value.replace(/(.*)(\d{2})/, '$1,$2');
  }
  function addLeftZero(value) {
    const length = value.length;
    if (length < 3) {
      const zeroAmount = 3 - length;
      for (let i = 0; i < zeroAmount; i++) {
        value = 0 + value;
      }
     }
    return value;
  }
  function addThousandSeparator(value) {
    const thousandSeparatorRegex = /(\d{1,2})(\d{3})(\.|\,.*)/;
    while (value.match(thousandSeparatorRegex)) {
	  	value = value.replace(thousandSeparatorRegex, '$1.$2$3');
    }
	  return value;
  }
  function removeLeftZero(value) {
    while(value.match(/^0/) && value.length > 3) {
      value = value.substr(1);
    }
    return value;
  }
}
.input-currency {
  text-align: right;
}
<input type="text" class="input-currency" maxlength="8" />
    
08.12.2017 / 12:14