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

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

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

Praveen Jeganathan报道

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


当前回答

    $(".numeric").keypress(function(event) {
  // Backspace, tab, enter, end, home, left, right
  // We don't support the del key in Opera because del == . == 46.
  var controlKeys = [8, 9, 13, 35, 36, 37, 39];
  // IE doesn't support indexOf
  var isControlKey = controlKeys.join(",").match(new RegExp(event.which));
  // Some browsers just don't raise events for control keys. Easy.
  // e.g. Safari backspace.
  if (!event.which || // Control keys in most browsers. e.g. Firefox tab is 0
      (49 <= event.which && event.which <= 57) || // Always 1 through 9
      (48 == event.which && $(this).attr("value")) || // No 0 first digit
      isControlKey) { // Opera assigns values for control keys.
    return;
  } else {
    event.preventDefault();
  }
});

这段代码对我来说工作得很好,我只需要在controlKeys数组中添加46来使用句号,虽然我不认为是最好的方法;)

其他回答

请在脚本底部添加:

if(this.value.length == 1 && this.value == 0)
 this.value = "";

我用了这个,效果很好。

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

更新

有一个新的非常简单的解决方案:

它允许你对文本<input>, 包括各种数字滤波器。这将正确处理 复制+粘贴,拖放,键盘快捷键,上下文菜单操作, 不可输入键,以及所有键盘布局。

看看这个答案或者自己在JSFiddle上试试。

jquery。数字插件

我已经成功地实现了许多形式与jquery。数字插件。

$(document).ready(function(){
    $(".numeric").numeric();
});

此外,这也适用于文本区域!

但是,请注意,Ctrl+A,复制+粘贴(通过上下文菜单)和拖放将不能正常工作。

HTML 5

随着对HTML 5标准的广泛支持,我们可以为输入元素使用模式属性和数字类型来限制只输入数字。在一些浏览器(特别是谷歌Chrome)中,它也可以限制粘贴非数字内容。关于number和其他更新的输入类型的更多信息可以在这里找到。

不再有插件,jQuery在1.7版本中实现了自己的jQuery. isnumeric()。

jQuery。isNumeric(value) 确定其参数是否为数字。

样品结果

$.isNumeric( "-10" );     // true
$.isNumeric( 16 );        // true
$.isNumeric( 0xFF );      // true
$.isNumeric( "0xFF" );    // true
$.isNumeric( "8e5" );     // true (exponential notation string)
$.isNumeric( 3.1415 );    // true
$.isNumeric( +10 );       // true
$.isNumeric( 0144 );      // true (octal integer literal)
$.isNumeric( "" );        // false
$.isNumeric({});          // false (empty object)
$.isNumeric( NaN );       // false
$.isNumeric( null );      // false
$.isNumeric( true );      // false
$.isNumeric( Infinity );  // false
$.isNumeric( undefined ); // false

下面是如何将isNumeric()与事件侦听器绑定在一起的示例

$(document).on('keyup', '.numeric-only', function(event) {
   var v = this.value;
   if($.isNumeric(v) === false) {
        //chop off the last char entered
        this.value = this.value.slice(0,-1);
   }
});

我第一次尝试用jQuery解决这个问题,但我不满意不需要的字符(非数字)实际上出现在输入字段刚刚被删除在keyup。

在寻找其他解决方案时,我发现:

整数(非负)

<script>
  function numbersOnly(oToCheckField, oKeyEvent) {
    return oKeyEvent.charCode === 0 ||
        /\d/.test(String.fromCharCode(oKeyEvent.charCode));
  }
</script>

<form name="myForm">
<p>Enter numbers only: <input type="text" name="myInput" 
    onkeypress="return numbersOnly(this, event);" 
    onpaste="return false;" /></p>
</form>

来源:https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers.onkeypress的例子 实例:http://jsfiddle.net/u8sZq/

小数点(非负)

为了允许一个小数点,你可以这样做:

<script>
  function numbersOnly(oToCheckField, oKeyEvent) {        
    var s = String.fromCharCode(oKeyEvent.charCode);
    var containsDecimalPoint = /\./.test(oToCheckField.value);
    return oKeyEvent.charCode === 0 || /\d/.test(s) || 
        /\./.test(s) && !containsDecimalPoint;
  }
</script>

来源:刚刚写了这个。似乎起作用了。 实例:http://jsfiddle.net/tjBsF/

其他定制

要允许输入更多的符号,只需将它们添加到充当基本字符代码过滤器的正则表达式中。 要实现简单的上下文限制,请查看输入字段(oToCheckField.value)的当前内容(状态)

一些你可能会感兴趣的事情:

只允许有一个小数点 只有在字符串的开头才允许使用减号。这将允许负数。

缺点

插入符号位置在函数内不可用。这大大减少了你可以实现的上下文限制(例如,没有两个相等的连续符号)。不知道最好的方法是什么。

我知道标题要求jQuery解决方案,但希望有人会发现这是有用的。