简体   繁体   中英

Special dot masked input HTML-JavaScript

I'm trying to achieve a special masked input in HTML using jQuery and themask plugin from Igor Escobar ( http://igorescobar.github.io/jQuery-Mask-Plugin/ )

I need write only numbers[0-9] and the following conversions:

input:

123456789

12345678

1234567

123456

desidered output:

123.456.789

12.345.678

1.234.567

123.456

Is possible achive this with that plugin? Or exist another way to do it? Thanks for reading :)

EDIT:

I did it using another plugin (Numeral.js): http://numeraljs.com/

This is my working code:

$("#myinput").blur(function() 
{
    this.value=numeral(this.value).format('0,0[.]00').replace(/\,/g, '.');
});

But I do not like to be validated at the end, ie (onblur), is there any way to do this on the fly? - That is, gradually validate (keypress).

You probably don't need a library for that. I kept jQuery but it's really used to select the input, so you definitely can ditch it quite easily.

$("#myinput").keyup(function(){
  // prevent every character except numbers
  if(!this.value.slice(-1).match(/^[0-9]+\.?[0-9]*$/) ){
    this.value = this.value.slice(0, -1);
    return;
  }
  // remove the dots, split the string and reverse it
  var a = this.value.replace(/\./g, '').split('').reverse();

  // start from 3 and as long as there's a number 
  // add a dot every three digits.
  var pos = 3;
  while(a[pos] !== undefined){
    a.splice(pos,0,'.');
    pos = pos + 4;
  }  
  // reverse, join and reassign the value
  this.value = a.reverse().join('');
});

You can try it yourself here and see if it does the job. Hope it helps.

EDIT : while the above code works it has some shortcomings, such as:

  • it does not work when copy/pasting
  • it does not allow moving with arrow keys
  • the cursor always goes to the end of the input, even when you are inserting a number in the middle.

As I needed it with full support for those cases I evolved it in a tiny script you can find on Github along with a demo and test spec.

$("#myinput").on('keyup keydown blur', function() {
    this.value=numeral(this.value).format('0,0[.]00').replace(/\,/g, '.');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM