Javascript 在没有额外插件的情况下使用 jquery 只允许文本框中的数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8635381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Allow only Numbers in text box using jquery with out extra plugins
提问by srini
i wanted to Allow only Numbers in text box using jquery/javascript with out extra plugins
我想在没有额外插件的情况下使用 jquery/javascript 只允许文本框中的数字
I have coded like :
我编码如下:
if ( event.keyCode == 46 || event.keyCode == 8 || (event.keyCode >=48 && event.keyCode <=57)) {
// let it happen, don't do anything
}
else {
// Ensure that it is a number and stop the keypress
event.preventDefault();
}
but it allows special characters like ! (Shift+1), @ (shift +2) etc.
但它允许特殊字符,如 ! (Shift+1)、@(Shift+2) 等。
can any body tell me the complete solution for this .. thanks in advance
任何人都可以告诉我完整的解决方案..提前致谢
采纳答案by srini
I solved by using the below code snippet. thanks for the inputs and help
我通过使用下面的代码片段解决了。感谢您的投入和帮助
$('input[etype="Number"]').keydown(function(event) {
if(event.shiftKey && ((event.keyCode >=48 && event.keyCode <=57)
|| (event.keyCode >=186 && event.keyCode <=222))){
// Ensure that it is a number and stop the Special chars
event.preventDefault();
}
else if ((event.shiftKey || event.ctrlKey) && (event.keyCode > 34 && event.keyCode < 40)){
// let it happen, don't do anything
}
else{
// Allow only backspace , delete, numbers
if (event.keyCode == 9 || event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 39 ||event.keyCode == 37
|| (event.keyCode >=48 && event.keyCode <=57)) {
// let it happen, don't do anything
}
else {
// Ensure that it is a number and stop the key press
event.preventDefault();
}
}
});
回答by Jonathan
This is unbreakable.
这是牢不可破的。
// 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));
});
回答by maxatmin.com
<input type="text" onKeyUp="$(this).val($(this).val().replace(/[^\d]/ig, ''))" />
This textbox allows only numbers. Even other characters are entered get disappeared.
此文本框只允许数字。即使输入其他字符也会消失。
回答by Umesh K.
The solution below:
下面的解决方案:
- allows numerics on number pad as well as keyboard
- does not allow ctrl,alt,shift key
- allows tab key to navigate to next text box
- allows back-space,delete,and arrow keys to move inside your textbox
- 允许数字键盘和键盘上的数字
- 不允许 ctrl,alt,shift 键
- 允许 Tab 键导航到下一个文本框
- 允许退格键、删除键和箭头键在文本框内移动
It does this by checking, step by step, to see if the event matches certain criteria.
它通过逐步检查事件是否符合某些标准来做到这一点。
$(".onlyNumerics").keydown(function (event) {
var num = event.keyCode;
if ((num > 95 && num < 106) || (num > 36 && num < 41) || num == 9) {
return;
}
if (event.shiftKey || event.ctrlKey || event.altKey) {
event.preventDefault();
} else if (num != 46 && num != 8) {
if (isNaN(parseInt(String.fromCharCode(event.which)))) {
event.preventDefault();
}
}
});
回答by Talha
You can use the new html5 input type of 'number'. It will only take the number as inputs. But it depends on the browser which supports it or not.
您可以使用新的 html5 输入类型“数字”。它只会将数字作为输入。但这取决于支持与否的浏览器。
<input type="number" />
you can also define the range of number as
您还可以将数字范围定义为
<input type="number" min="1" max="10" />
回答by Hearaman
See this bellow Example. You can prevent not numerical values by using Regex.
请参见下面的示例。您可以使用正则表达式来防止非数值。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function Numeric()
{
var field=document.iform.mob.value;
if (!field.match(/^[\-\+]?[\d\,]*\.?[\d]*$/))
{
alert("Enter only Numerics");
return false;
}
}
</script>
</head>
<body>
<form name="iform" method="post">
Add Your Mobile Number: <input type="text" name="mob" />
<br/>
<input type="submit" value="OK" onclick="return Numeric();" />
</form>
</body>
</html>
回答by TechMky
I'll just add another sample to the list.
我将在列表中添加另一个示例。
I have been using this in my projects for quite a while. The function is bind to keyup
event of the input[type=text]
我在我的项目中使用它已经有一段时间了。该函数绑定到keyup
事件input[type=text]
function handleInputKeyup(e) {
// if you want to enforce a minimum value
// declare somewhere else if need be
const DEFAULT_VALUE = 1
//don't do anything if the text is empty
if ($(this).val().length > 0) {
const currentValue = Number($(this).val())
if (isNaN(currentValue)) {
$(this).val(DEFAULT_VALUE);
return;
}
if (currentValue <= 0) {
$(this).val(DEFAULT_VALUE);
return;
}
}
}