Decimal mask on an ion-input type "number"

Asked

Viewed 1,332 times

2

I need to make a value mask (9 digits with 3 decimals), and when the user starts to enter the value, the field place the commas and point automatically, similar to what happens today in the bank systems, where in the field we have the 0,00 and as we enter the value goes to the left.

Example: I want to inform R $ 12,67

Input: 0,00

0,01

0,12

1.26

12,67

I’ve tried alternatives with external libs, but they only have effect on fields with type "Text", and because I’m developing for a tablet, I don’t want the keyboard to open with words, just numbers. My input type today is number, however on Samsung devices, not listed the option of "," or "." only the number.

My code is like this:

<ion-input type="number" #input name="quantidade" [(ngModel)]="quantidade" required></ion-input>
  • Use the type tel

  • It still doesn’t work @Robertofagundes. I need it to behave according to the example of the question.

  • 1

    I tried to do this in several ways, but always came across some problem (e.g., the user can paste numbers or click in the middle of the number and continue typing). The solution I found was to open a modal with a kind of calculator for the user to inform the value.

1 answer

0


I solved using a function same and changing the field type to "tel". It is not the best of ways, but I believe that I overcome the need for now.

<ion-input type="tel" inputmode="numeric" min="0" max="1000" (keyup)="updateList($event)" [(ngModel)]="valor"> </ion-input>

------JS ------

updateList(ev){

this.valor = this.currencyFormatted(ev.target.value)

}



currencyFormatted(amount) {

  var formatedValue = amount;
  var real = '';
  var cents = '';
  var temp = [];
  var i = 0;
  var j = 0;
  var k = 0;

  formatedValue = this.clearString(formatedValue.toString(), "0123456789");

  if(formatedValue.length > 3) {

    real = formatedValue.substr(0, formatedValue.length - 3);
    real = "" + parseInt(real, 10);
    cents = formatedValue.substr(formatedValue.length - 3, 3);

    if(real.length > 3) {
      temp = [];
      for(i = real.length - 1, j = 1, k = 0; i > 0 ; i--, j++) {
        if((j % 3) == 0) {
          temp.push(real.substr(i, 3));
          k++;
        }
      }
      temp.reverse();
      real = real.substr(0, real.length - (3 * k)) + '.' + temp.join('.');
    }
    formatedValue = real + ',' + cents;
  }
  return formatedValue;
}



clearString(value, validCharacters) {
  var result = '';
  var index = -1;
  var i = 0;

  for(i = 0; i < value.length; i++) {
    index = validCharacters.indexOf(value.charAt(i));

   if(index > -1) {
      result += validCharacters.charAt(index);
    }
  }
  return result;
}

Browser other questions tagged

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