maxlength in coin mask

Asked

Viewed 253 times

2

I’m wearing this coin mask, it works until well put a maxlength in the input it does not limit the amount 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 (does not disturb much, but I find it boring), the tab doesn’t work when I’m in this field.

4 answers

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 maxlength value in the input the round wheel script without changing 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') ?>">

0

From a glance at this code I made, it solves everything with regex, I think it still gives to improve and you can understand well because it has everything separator 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" />

0

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

The len < 7 means you’re only allowed to type up to 6 numbers, adding to the 2 decimal and thousand separator characters that are automatically added, 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 (does not disturb much, but I find it boring), the tab doesn’t work when I’m in this field.

In the example above, the tab works perfectly. This information needs more details for resolution. Post in the comments below more information about the problem so we can solve.

  • Because if(len > 7) if the maxlength="8"

  • @Leocaracciolo Where did you see this? rsrs

  • expired glasses, hahahah

  • @Leocaracciolo I too... sometimes I read wrong rs

  • I opened an answer to that post

  • @Leocaracciolo Good luck! :)

Show 1 more comment

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 the INPUT:

<input type="text" onkeyup="moeda(this);" maxlength="9">
  • Running on https://jsfiddle.net/yfk3zg2g/

Browser other questions tagged

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