我正在创建一个网页,其中我有一个输入文本字段,我想只允许数字字符,如(0,1,2,3,4,5…9)0-9。

我如何使用jQuery做到这一点?


当前回答

对我来说更简单的是

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

其他回答

只需要在Jquery中应用此方法,您可以验证您的文本框只接受数字。

function IsNumberKeyWithoutDecimal(element) {    
var value = $(element).val();
var regExp = "^\\d+$";
return value.match(regExp); 
}

试试这个解决方案

很多人在这里使用键码属性,这是不容易记住的。如果你没有语言环境问题,那么你可以简单地使用键,这实际上是用户键入的输入。

看这把小提琴

$("#txt").on("keypress",function(e){ console.log("Entered Key is " + e.key); switch (e.key) { case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": case "0": case "Backspace": return true; break; case ".": if ($(this).val().indexOf(".") == -1) //Checking if it already contains decimal. You can Remove this condition if you do not want to include decimals in your input box. { return true; } else { return false; } break; default: return false; } }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> Enter Value <input id="txt" type="text" />

然后查看下面的简单代码。

请注意,此示例还包含对十进制输入的验证。

对于这个问题,它不是必需的,所以您可以简单地删除大小写“。”以删除小数的条目。

为了更详细地说明#3的答案,我将执行以下操作(注意:仍然不支持通过键盘或鼠标粘贴操作):

$('#txtNumeric').keypress(
            function(event) {
                //Allow only backspace and delete
                if (event.keyCode != 46 && event.keyCode != 8) {
                    if (!parseInt(String.fromCharCode(event.which))) {
                        event.preventDefault();
                    }
                }
            }
        );

使用jQuery.validate做一些相当简单的事情

$(document).ready(function() {
    $("#formID").validate({
        rules: {
            field_name: {
                numericOnly:true
            }
        }
    });
});

$.validator.addMethod('numericOnly', function (value) {
       return /^[0-9]+$/.test(value);
}, 'Please only enter numeric values (0-9)');

你可以尝试HTML5数字输入:

<input type="number" value="0" min="0"> 

对于不兼容的浏览器,可以使用Modernizr和Webforms2。