什么是限制“数字”仅输入文本框的最佳方法?

我在找一些允许小数点的东西。

我看到很多这样的例子。但还没决定用哪一种。

Praveen Jeganathan报道

不再有插件,jQuery在1.7版本中实现了自己的jQuery. isnumeric()。 参见:https://stackoverflow.com/a/20186188/66767


当前回答

在这里找到了一个很好的解决方案http://ajax911.com/numbers-numeric-field-jquery/

我只是按照我的要求把“键上”改为“键下”

其他回答

不需要长代码的数字输入限制,只是尝试这段代码。 它还接受有效的int和float值。

Javascript方法

onload = function () { var ele = document.querySelectorAll('.number-only')[0]; 避署。Onkeypress =函数(e) { 如果(isNaN (this.value + " " + String.fromCharCode (e.charCode))) 返回错误; } 避署。Onpaste = function(e){ e.preventDefault (); } } <p>只接受有效的int和float值的输入框 <input class="number-only" type=text />

jQuery方法

$(函数(){ $ (' .number-only ') .keypress(函数(e) { if(isNaN(this.value+""+String.fromCharCode(e.charCode)))返回false; }) .on("剪切复制粘贴",函数(e){ e.preventDefault (); }); }); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本> <p>只接受有效的int和float值的输入框 <input class="number-only" type=text />

更新

上面的答案适用于最常见的用例——将输入验证为数字。

但是下面是特殊用例的代码片段

允许负数 在删除之前显示无效的击键。

$(function(){ $('.number-only').keyup(function(e) { if(this.value!='-') while(isNaN(this.value)) this.value = this.value.split('').reverse().join('').replace(/[\D]/i,'') .split('').reverse().join(''); }) .on("cut copy paste",function(e){ e.preventDefault(); }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p> Input box that accepts only valid int and float values.</p> <input class="number-only" type=text />

我用了这个,效果很好。

ini=$("#id").val();
a=0;
$("#id").keyup(function(e){
    var charcode = (e.which) ? e.which : e.keyCode;
    // for decimal point
    if(!(charcode===190 || charcode===110))
    {           // for numeric keys andcontrol keys
        if (!((charcode>=33 && charcode<=57) || 
        // for numpad numeric keys
        (charcode>=96 && charcode<=105) 
        // for backspace
        || charcode==8)) 
        {
            alert("Sorry! Only numeric values allowed.");
            $("#id").val(ini);
        }
        // to include decimal point if first one has been deleted.
        if(charcode===8)
        {
            ini=ini.split("").reverse();
            if(ini[0]==".")
            a=0;                 
        }
    }
    else
    {
        if(a==1)
        {
            alert("Sorry! Second decimal point not allowed.");
            $("#id").val(ini);
        }
        a=1;
    }
    ini=$("#id").val();
});


find keycodes at http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

有一个很好的jquery插件叫做jquery Mask plugin,设计用于在表单字段和html元素上做蒙版,但你也可以用它来简单地定义什么类型的数据可以在字段中输入:

$('.numeric-input').mask('0#');

现在只有数字将被允许在您的表单字段。

   window.jQuery.fn.ForceNumericOnly =
       function () {

           return this.each(function () {
               $(this).keydown(function (event) {
                   // Allow: backspace, delete, tab, escape, and enter
                   if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
                       // Allow: Ctrl+A
                       (event.keyCode == 65 && event.ctrlKey === true) ||
                       // Allow: home, end, left, right
                       (event.keyCode >= 35 && event.keyCode <= 39)) {
                       // let it happen, don't do anything
                       return;
                   } else {
                       // Ensure that it is a number and stop the keypress
                       if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
                           event.preventDefault();
                       }
                   }
               });
           });
       };

把这个应用到你想要的所有输入上:

$('selector').ForceNumericOnly();

您可以通过添加模式对文本输入使用HTML5验证。不需要使用regex或keyCodes手动验证。

<input type="text" pattern="[0-9.]+" />

$("input[type=text][pattern]").on("input", function () {
    if (!this.checkValidity())
        this.value = this.value.slice(0, -1);
});

对于输入[type=number]的解决方案,请参阅我的完整答案