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


当前回答

input type="number"是一个HTML5属性。

在另一种情况下,这将帮助你:

function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : evt.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}

<input type="number" name="somecode" onkeypress="return isNumberKey(event)"/>

其他回答

请记住地区差异(欧洲人使用句点和逗号的方式与美国人相反),加上负号(或将数字用括号括起来表示负数的习惯),加上指数符号(我正要谈到这个)。

有一个更简单的解决方案,之前没有人提到过:

inputmode="numeric"

阅读更多信息:https://css-tricks.com/finger-friendly-numerical-inputs-with-inputmode/

只是使用jQuery的另一个变体

$(".numeric").keypress(function() {
    return (/\d/.test(String.fromCharCode(event.which) ))
});

解决这个问题的一个简单方法是实现一个jQuery函数来验证文本框中输入的字符,例如:

你的html代码:

<input class="integerInput" type="text">

和使用jQuery的js函数

$(function() {
    $('.integerInput').on('input', function() {
      this.value = this.value
        .replace(/[^\d]/g, '');// numbers and decimals only

    });
});

$(函数(){ $('.integerInput').on('input', function() { 这一点。Value = this.value .replace(/[^\d]/g, ");//只能输入数字和小数 }); }); <脚本 src = " https://code.jquery.com/jquery-2.2.4.min.js " 诚信= " sha256-BbhdlvQf / xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44 = " crossorigin =“匿名”> > < /脚本 <input type="text" class="integerInput"/>

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

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方法慢几微秒。

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

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