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

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


当前回答

function Numbers(e)
{
    if($.browser.msie)
    {
        if(e.keyCode > 47 && e.keyCode < 58)
            return true;
        else
            return false;
    }
    else
    {
        if((e.charCode > 47 && e.charCode < 58) || (e.charCode == 0))
            return true;
        else
            return false;
    }
}

我希望这在所有浏览器上都能工作。

其他回答

使用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)');

这将在添加非数字字符时保持先前的值。

$(document).on('input', '.digit-input', function() {
    var prevVal = $(this).attr('ov') ? $(this).attr('ov') : '';
    var newVal = this.value.replace(/[^0-9]/g, '');
    this.value = newVal != '' ? newVal : prevVal;
    $(this).attr('ov', this.value);
});

$(文件)。据(’input’'。digit-input',函数(){ var prevVal = $(this).attr('ov') ?$(this).attr('ov'): "; var newVal = this.value。回想起(^ [0 - 9]/ g '); this。= = " ? "newVal: prevVal; $ (this)。attr(’ov’this.value); }); < script " src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js " > / < script > <input type="text" class=" digital -input">

这里有两种不同的方法:

允许有小数点的数值 允许没有小数点的数值

方法1:

$ (" # approach1”)。上(“keypress keyup blur”,function (e) (这个美元)。瓦尔(这)。瓦尔(美元)。replace(0 - 9 \。- [^]/ g,”); 如果(e .哪! = 46 | |美元(这)。瓦尔indexOf()。 ('.') != - 1) &&(事件)。哪种< 48 | |事件。哪个> 57) 事件。preventDefault (); 的 }); <剧本剧本src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js " > < / > <h2>Numeric与decimal point</h2><br/> <跨越>输入数量< /跨越> <输入类型=“文本”

方法2:

$ (" # approach2”)。上(“keypress keyup blur”,功能(事件) (这个美元)。瓦尔(这)。瓦尔(美元)。replace (- [^ \ d]。+ -”、“); 如果(事件。哪种< 48 | |事件。哪个> 57) 事件。preventDefault (); 的 }); <剧本剧本src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js " > < / > <h2>Numeric without decimal point</h2><br/> <跨越>输入数量< /跨越> <输入类型=“文本”

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

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

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

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

$(document).ready(function() {
    $("#txtboxToFilter").keydown(function(event) {
        // Allow only backspace and delete
        if ( event.keyCode == 46 || event.keyCode == 8 ) {
            // let it happen, don't do anything
        }
        else {
            // Ensure that it is a number and stop the keypress
            if (event.keyCode < 48 || event.keyCode > 57 ) {
                event.preventDefault(); 
            }   
        }
    });
});

来源:http://snipt.net/GerryEng/jquery-making-textfield-only-accept-numeric-values