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

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

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

Praveen Jeganathan报道

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


当前回答

我有一段代码,它很好地完成了这项工作。

 var prevVal = '';
$(".numericValue").on("input", function (evt) {
    var self = $(this);
    if (self.val().match(/^-?\d*(\.(?=\d*)\d*)?$/) !== null) {
        prevVal = self.val()
    } else {
        self.val(prevVal);
    }
    if ((evt.which != 46 || self.val().indexOf('.') != -1) && (evt.which < 48 || evt.which > 57) && (evt.which != 45 && self.val().indexOf("-") == 0)) {
        evt.preventDefault();
    }
});

其他回答

我用了这个,效果很好。

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

我使用了James Nelli的答案,并添加了onpaste="return false;"(Håvard Geithus)以确保输入中只输入整数。即使你尝试粘贴,它也不会允许。

您可以通过添加模式对文本输入使用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]的解决方案,请参阅我的完整答案

这很简单,我们已经有一个javascript内置函数“isNaN”在那里。

$("#numeric").keydown(function(e){
  if (isNaN(String.fromCharCode(e.which))){ 
    return false; 
  }
});

如果你使用的是HTML5,你就不需要花大力气去执行验证。只要用——

<input type="number" step="any" />

step属性允许小数点有效。