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

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


当前回答

使用JavaScript函数isNaN,

if (isNaN($('#inputid').val()))

if (isNaN(document.getElementById('inputid').val()))

if (isNaN(document.getElementById('inputid').value))

更新: 这里有一篇很好的文章谈论它,但使用jQuery:限制输入在HTML文本框的数值

其他回答

您可以使用以下代码。

<input type=“text” onkeypress=“return event.charCode >= 48 && event.charCode <= 57”>

这里有两种不同的方法:

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

方法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/> <跨越>输入数量< /跨越> <输入类型=“文本”

这似乎牢不可破。

// Prevent NULL input and replace text.
$(document).on('change', 'input[type="number"]', function (event) {
    this.value = this.value.replace(/[^0-9\.]+/g, '');
    if (this.value < 1) this.value = 0;
});

// Block non-numeric chars.
$(document).on('keypress', 'input[type="number"]', function (event) {
    return (((event.which > 47) && (event.which < 58)) || (event.which == 13));
});

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

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

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

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

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

$(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">