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

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


当前回答

这是我不久前创建的一个快速解决方案。你可以在我的文章中了解更多:

http://ajax911.com/numbers-numeric-field-jquery/

$("#textfield").bind("keyup paste", function(){
    setTimeout(jQuery.proxy(function() {
        this.val(this.val().replace(/[^0-9]/g, ''));
    }, $(this)), 0);
});

其他回答

你可以像这样使用on input事件:

$(document).on("input", ".numeric", function() {
    this.value = this.value.replace(/\D/g,'');
});

但是,这个代码特权是什么?

它适用于移动浏览器(keydown和keyCode有问题)。 它也适用于AJAX生成的内容,因为我们使用了“on”。 比按下键更好的性能,例如在粘贴事件上。

使用下面简单的jQuery,在文本框中只允许数字字符。您不需要手动筛选所有特殊字符,因此不会有遗漏某些特殊字符的危险。这将只允许数字0-9:(将下面的代码放在document ready中,并根据您的数字文本字段类名更改类名。)

//Event of data being keyed in to textbox with class="numericField".
$(".numericField").keyup(function() {
    // Get the non Numeric char that was enetered
    var nonNumericChars = $(this).val().replace(/[0-9]/g, '');                                  
    // Now set the value in text box 
    $(this).val( $(this).val().replace(nonNumericChars, ''));    

});

你可以尝试HTML5数字输入:

<input type="number" placeholder="enter the number" min="0" max="9">

这个输入标记元素现在只接受0到9之间的值 min属性设置为0,Max属性设置为9。

欲了解更多信息,请访问http://www.w3schools.com/html/html_form_input_types.asp

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

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

检查输入值是否为数字的简单方法是:

var checknumber = $('#textbox_id').val();

    if(jQuery.isNumeric(checknumber) == false){
        alert('Please enter numeric value');
        $('#special_price').focus();
        return;
    }