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

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

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

Praveen Jeganathan报道

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


当前回答

你看不到字母的神奇出现和消失的关键下来。这也适用于鼠标粘贴。

$('#txtInt').bind('input propertychange', function () {
    $(this).val($(this).val().replace(/[^0-9]/g, ''));
});

其他回答

保持插入符号在输入中的位置的其他方法:

$(document).ready(function() {
  $('.numbersOnly').on('input', function() {
    var position = this.selectionStart - 1;

    fixed = this.value.replace(/[^0-9\.]/g, '');  //remove all but number and .
    if(fixed.charAt(0) === '.')                  //can't start with .
      fixed = fixed.slice(1);

    var pos = fixed.indexOf(".") + 1;
    if(pos >= 0)
      fixed = fixed.substr(0,pos) + fixed.slice(pos).replace('.', '');  //avoid more than one .

    if (this.value !== fixed) {
      this.value = fixed;
      this.selectionStart = position;
      this.selectionEnd = position;
    }
  });
});

优点:

用户可以使用方向键、退格键、删除键、… 当你想要粘贴数字的时候就可以了

Plunker:演示工作

你可以使用来自decorplanit.com的autoNumeric。它们对数字、货币、舍入等都有很好的支持。

我曾经在IE6环境下使用过,只做了一些css调整,结果还算成功。

例如,可以定义一个css类numericInput,它可以用来用数字输入掩码装饰字段。

改编自autoNumeric网站:

$('input.numericInput').autoNumeric({aSep: '.', aDec: ','}); // very flexible!

如果希望限制输入(而不是验证),可以使用键事件。就像这样:

<input type="text" class="numbersOnly" value="" />

And:

jQuery('.numbersOnly').keyup(function () { 
    this.value = this.value.replace(/[^0-9\.]/g,'');
});

这将立即让用户知道他们不能输入alpha字符等,而不是在验证阶段之后。

您仍然需要验证,因为输入可能是通过鼠标剪切和粘贴来填充的,也可能是通过表单自动补全程序填充的,这可能不会触发键事件。

/* 这是我的跨浏览器版本 如何允许只有数字(0-9)在HTML输入框使用jQuery? * /

$("#inputPrice").keydown(function(e){
    var keyPressed;
    if (!e) var e = window.event;
    if (e.keyCode) keyPressed = e.keyCode;
    else if (e.which) keyPressed = e.which;
    var hasDecimalPoint = (($(this).val().split('.').length-1)>0);
    if ( keyPressed == 46 || keyPressed == 8 ||((keyPressed == 190||keyPressed == 110)&&(!hasDecimalPoint && !e.shiftKey)) || keyPressed == 9 || keyPressed == 27 || keyPressed == 13 ||
             // Allow: Ctrl+A
            (keyPressed == 65 && e.ctrlKey === true) ||
             // Allow: home, end, left, right
            (keyPressed >= 35 && keyPressed <= 39)) {
                 // let it happen, don't do anything
                 return;
        }
        else {
            // Ensure that it is a number and stop the keypress
            if (e.shiftKey || (keyPressed < 48 || keyPressed > 57) && (keyPressed < 96 || keyPressed > 105 )) {
                e.preventDefault();
            }
        }

  });

也允许负数

下面的代码也接受负数

HTML

<input type="text" name="myText" />

JS

var pastValue, pastSelectionStart, pastSelectionEnd;

$("input").on("keydown", function() {
    pastValue          = this.value;
    pastSelectionStart = this.selectionStart;
    pastSelectionEnd   = this.selectionEnd;
}).on("input propertychange", function() {

    if ( this.value.length > 0 && $.isNumeric(this.value) == false && this.value != '-' ) {
        this.value          = pastValue;
        this.selectionStart = pastSelectionStart;
        this.selectionEnd   = pastSelectionEnd;
    }
}).on('blur', function(){
        if(this.value == '-')
            this.value = '';
});