特殊点屏蔽输入HTML JavaScript

特殊点屏蔽输入HTML JavaScript,javascript,jquery,html,masking,Javascript,Jquery,Html,Masking,我正试图使用来自igorescobar()的jQuery和任务插件在HTML中实现一个特殊的屏蔽输入 我只需要写数字[0-9]和以下转换: 输入: 123456789 12345678 1234567 123456 指定输出: 123.456.789 12.345.678 1.234.567 123.456 有可能用那个插件实现这个吗? 或者存在另一种方法来实现它? 感谢阅读:) 编辑: 我是用另一个插件(numeric.js)实现的: 这是我的工作代码: $("#myinput").blur(

我正试图使用来自igorescobar()的jQuery和任务插件在HTML中实现一个特殊的屏蔽输入

我只需要写数字[0-9]和以下转换:

输入:

123456789

12345678

1234567

123456

指定输出:

123.456.789

12.345.678

1.234.567

123.456

有可能用那个插件实现这个吗? 或者存在另一种方法来实现它? 感谢阅读:)

编辑:

我是用另一个插件(numeric.js)实现的:

这是我的工作代码:

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

但我不喜欢在最后被验证,即(onblur),有没有任何方法可以在运行中进行验证也就是说,逐步验证(按键)。

您可能不需要库。我保留了jQuery,但它实际上是用来选择输入的,因此您肯定可以很容易地放弃它

$("#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('');
});
你可以自己试一试,看看它是否管用。希望能有帮助

编辑:虽然上述代码有效,但它也有一些缺点,例如:

  • 复制/粘贴时不起作用
  • 它不允许使用箭头键移动
  • <> LI>即使输入中间的数字,光标也会一直到输入的末尾。

由于我需要对这些情况提供全面支持,我将它发展成一个小脚本,您可以在上面找到它,还有一个演示和测试规范。

$(“.yourclass”).mask('099.099.099.099')?谢谢你的回答,但是如果输入是“12345678”,那么这个代码会导致这个“123.456.78”,我希望“12.345.678”使用
keyup
而不是
blur
@MelanciaUK,当我这样做时会发生一些奇怪的事情。试试看,当我这么做的时候,会有奇怪的事情发生。试试看。并且,请在代码的最后添加“;”。很好,没有插件,只有jQuery!聪明!
$("#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('');
});