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

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

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

Praveen Jeganathan报道

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


当前回答

也允许负数

下面的代码也接受负数

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 = '';
});

其他回答

你可以使用带有number()方法的Validation插件。

$("#myform").validate({
  rules: {
    field: {
      required: true,
      number: true
    }
  }
});

请在脚本底部添加:

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

我使用这个函数,它工作得很好

$(document).ready(function () {
        $("#txt_Price").keypress(function (e) {
            //if the letter is not digit then display error and don't type anything
            //if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) 
            if ((e.which != 46 || $(this).val().indexOf('.') != -1) && (e.which < 48 || e.which > 57)) {
                //display error message
                $("#errmsg").html("Digits Only").show().fadeOut("slow");
                return false;
            }
        });
    }); 

下面是我用来阻止击键的。这只允许数字0-9和小数点。易于实现,不需要大量代码,并且工作起来很有魅力:

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

<input value="" onkeypress="return isNumberKey(event)">

也允许负数

下面的代码也接受负数

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 = '';
});