在<input>中禁用零作为第一个字母

tae*_*esu 8 javascript jquery

下面的代码禁用0作为第一个字符#foo.
但是,您可以通过键入123,然后拖动以选择123和放置来绕过此0.(或ctrl+a输入)

有办法阻止这种情况吗?

 $('input#foo').keypress(function(e){ 
  if (this.value.length == 0 && e.which == 48 ){
   return false;
   }
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="foo" />
Run Code Online (Sandbox Code Playgroud)

Sea*_*ell 10

我会处理输入,属性更改和粘贴事件.然后使用正则表达式匹配任何以0开头的内容,并将当前值替换为减去前导0的值.

http://jsfiddle.net/SeanWessell/5qxwpv6h/

$('input ').on('input propertychange paste', function (e) {
    var val = $(this).val()
    var reg = /^0/gi;
    if (val.match(reg)) {
        $(this).val(val.replace(reg, ''));
    }
});
Run Code Online (Sandbox Code Playgroud)

凯文报告的错误修复/根据佳能的推荐更新:

http://jsfiddle.net/SeanWessell/5qxwpv6h/2/

$('input').on('input propertychange paste', function (e) {
    var reg = /^0+/gi;
    if (this.value.match(reg)) {
        this.value = this.value.replace(reg, '');
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 错误:键入`123000`然后删除`123`.你剩下的是'00`.我建议使用正则表达式`^ 0 +`. (3认同)
  • @SeanWessell因此,您不必更新正则表达式,而是决定使用while循环.最重要的是,您将为每个循环条件_and_它的主体实例化一个新的jQuery对象.所以,**1.:**为什么你使用`$(this).val()`而不是`this.value`?这是不必要的开销.**2.:**如果你在`$(this)`上_insist_,你为什么不缓存你的jQuery对象?**3.:**为什么要循环而不是只更新正则表达式?我很担心这个答案吸引了如此多的赞成. (2认同)