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

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


当前回答

我建议检查事件。我也带着。如果设置为true,用户可能会执行类似cmd-A的操作来选择字段中的所有文本。你也应该承认这一点。

其他回答

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

jQuery("#no_of").keyup(function(e){
    var temp_s= jQuery("#no_of").val();
    var multiply_val= temp_s*10;
    jQuery("#ex-r").html(multiply_val);
});

使用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验证。不需要使用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]…

[type="number"]的问题是我们不能只删除最后的无效字符。当输入无效时,用户代理返回一个空字符串。

来自W3C HTML5规范:

如果元素的值不是有效的浮点数,则 将其设置为空字符串。

https://dev.w3.org/html5/spec-LC/number-state.html#number-state

这意味着我们需要一种方法来手动存储之前的输入值。

对于数字输入,解是这样的:

$("input[type=number], input[type=text][pattern]").on("input", function () {
    if (!this.checkValidity())
        this.value = $(this).data("current-valid") || "";
    else
        $(this).data("current-valid", this.value);
});

不幸的是,这将不能在IE和EDGE上工作。对于这些浏览器,我们需要使用上面的模式解决方案。然而,您仍然可以使用这个简单的填充数字输入。

$("input[type=number]").attr("type", "text").attr("pattern", "[0-9.]+");

尝试在HTML代码中,它自己像onkeypress和onpast

<input type="text" onkeypress="return event.charCode >= 48 && event.charCode <= 57" onpaste="return false">

为什么这么复杂?你甚至不需要jQuery,因为有一个HTML5的模式属性:

<input type="text" pattern="[0-9]*">

最酷的是它在移动设备上显示了一个数字键盘,这比使用jQuery好多了。