2014-06-17 27 views
0

我想将输入限制为键入的数字,但最多只有一个数字。例如'0','1','2','9',但不是'12'或'99'。将表单输入限制为单个数字

我的问题是我可以在我当前的代码中输入任何数量的数字。

我现在使用的代码如下所示。 Here is a JSFiddle where you can test it.

$('.numbersOnly').keypress(function(e) { 
      var verified = (e.which == 8 || e.which == undefined || e.which == 0) ? null : String.fromCharCode(e.which).match(/[^0-9]/); 
      if (verified) {e.preventDefault();} 
    }); 
+0

http://jasny.github.io/bootstrap/javascript/#inputmask - 可能有助于(或类似的插件) – Blazemonger

+0

到底是什么输入所需的格式? –

+0

仍不清楚。是“9.”好吗?那么“.9”呢?如果你只想让数字0到9,请说出来。 –

回答

0

我能想到的最简单的方法:

$('.numbersOnly').keypress(function(e) { 
      var allowed = /[^0-9]/; 
      if (!/\./.test($(this).val())) allowed = /[^0-9\.]/; 

      var verified = (e.which == 8 || e.which == undefined || e.which == 0) ? null : String.fromCharCode(e.which).match(allowed); 
      if (verified) {e.preventDefault();} 
    });