有一个快速的方法来设置HTML文本输入(<input type=text />),只允许数字击键(加上'.')?


当前回答

更安全的方法是检查输入的值,而不是劫持按键并试图过滤keycode。

通过这种方式,用户可以自由使用键盘箭头、修改键、退格键、删除键、使用非标准键键、使用鼠标粘贴、使用拖放文本,甚至使用辅助输入。

下面的脚本允许正数和负数

1
10
100.0
100.01
-1
-1.0
-10.00
1.0.0 //not allowed

var input = document.getElementById('number'); 输入。Onkeyup =输入。onchange = enforcfloat; //强制只能输入浮点数 函数enforceFloat() { Var valid = /^\-?\d+\. d*$|^\-?[\d]*$/; var = / \ \ d + \数量。* | \ \ d - (\ d) * | (\ d) + \ \ [d]。* | (\ d) + /; If (!valid.test(this.value)) { Var n = this.value.match(number); 这一点。Value = n ?N[0]:“; } } <input id="number" value="-3.1415" placeholder="Type a number" autofocus> .

编辑:我删除了我的旧答案,因为我认为它现在已经过时了。

其他回答

这是一个改进的函数:

function validateNumber(evt) {
  var theEvent = evt || window.event;
  var key = theEvent.keyCode || theEvent.which;
  if ((key < 48 || key > 57) && !(key == 8 || key == 9 || key == 13 || key == 37 || key == 39 || key == 46) ){
    theEvent.returnValue = false;
    if (theEvent.preventDefault) theEvent.preventDefault();
  }
}

这里的大多数答案都有使用关键事件的缺点。

许多答案会限制你使用键盘宏进行文本选择、复制+粘贴和更多不必要的行为,其他的似乎依赖于特定的jQuery插件,这是用机关枪杀苍蝇。

这个简单的解决方案似乎最适合我跨平台,不管输入机制(击键,复制+粘贴,右键单击复制+粘贴,语音到文本等)。所有文本选择键盘宏仍然可以工作,它甚至会限制通过脚本设置非数字值的能力。

function forceNumeric(){
    var $input = $(this);
    $input.val($input.val().replace(/[^\d]+/g,''));
}
$('body').on('propertychange input', 'input[type="number"]', forceNumeric);

这里有一个简单的例子,它只允许有一个小数,不能再多了。输入事件使用regex替换基于以下两种模式的文本:

删除任何不是数字或点的东西 删除点的任何第二个实例

<input type="text" oninput="this. "Value = this.value.replace(/[^0-9。.replace) / g,”) (/(\..*?)\..* / g, 1美元);”/>

正如下面有人评论的那样,上面的解决方案不处理前导零。如果你的特定用例要求这些是不允许的,你可以像这样添加到上面的模式:

<input type="text" oninput="this. "Value = this.value.replace(/[^0-9。.replace) / g,”) (/(\..*?)\..* / g, 1美元).replace(/ ^ 0 ^。] /, ' 0 ');“/>

这将允许0.123或。123,但不允许0123或00.123。

<input type="tel" 
          onkeypress="return onlyNumberKey(event)">

脚本内标记

function onlyNumberKey(evt) { 
      
      // Only ASCII charactar in that range allowed 
      var ASCIICode = (evt.which) ? evt.which : evt.keyCode 
      if (ASCIICode > 31 && (ASCIICode < 48 || ASCIICode > 57)) 
          return false; 
      return true; 
} 

当涉及到万无一失的用户体验时,人们应该总是尝试保持一个“用户智力”的参考点。

While neglecting everything other than numbers, a dot and a hyphen would seem like the perfect choice, you should also consider letting them enter any content, and when they're done, purify the input; if not a valid number, show error. This method would make sure no matter what the user manages to do, the result will always be valid. If the user is naive enough not to understand the warnings and error messages, pressing a button and seeing that nothing happens (as in keycode comparison) will only confuse him/her more.

同样,对于表单,验证和错误消息显示几乎是必需的。所以,这些条款可能已经存在了。算法如下:

On losing-focus or form-submission, do following. 1.1. Read content from the input and apply parseFloat to result 1.2. If the result is a Non-accessible-Number (NaN), reset the input field and pop-up an error message: "Please enter a valid number: eg. 235 or -654 or 321.526 or -6352.646584". 1.3. Else, if String(result)!==(content from input), change value of the field to result and show warning message: "The value you entered have been modified. Input must be a valid number: eg. 235 or -654 or 321.526 or -6352.646584". For a field that cannot allow any unconfirmed value, then this condition may be added to step 1.2. 1.4. Else, do nothing.

该方法还为您提供了额外的优势,可以根据最小值、最大值、小数点等执行验证。只需要对步骤1.2之后的结果执行这些操作。

缺点:

输入将允许用户输入任何值,直到焦点丢失或表单提交为止。但如果填写说明足够清楚,90%的情况下可能不会出现这种情况。 如果步骤1.3用于显示警告,则可能会被用户忽略,并可能导致无意的输入提交。抛出错误或正确显示警告可以解决这个问题。 速度。这可能比regex方法慢几微秒。

优点: 假设用户有基本的阅读和理解知识,

高度可定制的选项。 工作跨浏览器和独立于语言。 利用表单中已有的功能来显示错误和警告。