如何仅允许使用jQuery的HTML输入框中的数字(0-9)? [英] How to allow only numeric (0-9) in HTML inputbox using jQuery?
问题描述
我正在创建一个网页,其中有一个输入文本字段,我只想让数字字符(如0,1,2,3,4,5 ... 9)0-9。
如何使用jQuery执行此操作?
看看这个插件(texotela的数字jquery插件叉)。 这个(jStepper)是另一个。
< a href =http://snipt.net/GerryEng/jquery-making-textfield-only-accept-numeric-values =noreferrer>如果你想自己构建它,这是一个链接。
$(document).ready(function(){
$(#txtboxToFilter)。keydown(function (e){
//允许:退格,删除,制表符,转义,输入和。
if($ .inArray(e.keyCode,[46,8,9,27,13,110, 190])!== -1 ||
//允许:Ctrl + A,Command + A
(e.keyCode === 65&&(e.ctrlKey === true | | e.metaKey === true))||
// Allow:home,end,left,right,down,up
(e.keyCode> = 35&& e.keyCode < = 40)){
//让它发生,不要做任何事
return;
}
//确保它是一个数字并停止按键$ b(b)如果((e.shiftKey ||(e.key代码< 48 || e.keyCode> 57))&& (e.keyCode< 96 || e.keyCode> 105)){
e.preventDefault();
}
});
});
注意:如果您的网页使用HTML5,则可以使用内置的< ; input type =number>
并使用 min
和 max
控制最小值和最大值。
以下是最小化的,并允许使用 CTRL + X , CTRL + C 和 CTRL + V
< script src =https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js>< / script>< div id = staticParent> < input id =childtype =textarea/>< / div>
b
I am creating a web page where I have an input text field in which I want to allow only numeric characters like (0,1,2,3,4,5...9) 0-9.
How can I do this using jQuery?
Have a look at this plug-in (Fork of texotela's numeric jquery plugin). This (jStepper) is another one.
This is a link if you want to build it yourself.
$(document).ready(function() {
$("#txtboxToFilter").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A, Command+A
(e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
// Allow: home, end, left, right, down, up
(e.keyCode >= 35 && e.keyCode <= 40)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
});
NOTE: If your webpage uses HTML5, you can use the built in <input type="number">
and use the min
and max
properties to control the minimum and maximum value.
The following is minimized and also allows for use of CTRL+X, CTRL+C, and CTRL+V
$(function() {
$('#staticParent').on('keydown', '#child', function(e){-1!==$.inArray(e.keyCode,[46,8,9,27,13,110,190])||(/65|67|86|88/.test(e.keyCode)&&(e.ctrlKey===true||e.metaKey===true))&&(!0===e.ctrlKey||!0===e.metaKey)||35<=e.keyCode&&40>=e.keyCode||(e.shiftKey||48>e.keyCode||57<e.keyCode)&&(96>e.keyCode||105<e.keyCode)&&e.preventDefault()});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="staticParent">
<input id="child" type="textarea" />
</div>
这篇关于如何仅允许使用jQuery的HTML输入框中的数字(0-9)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!