在 JavaScript 中只允许数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11114073/
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 JavaScript
提问by itzArun
Possible Duplicate:
HTML Text Input allow only Numeric input
可能重复:
HTML 文本输入仅允许数字输入
I used this script
我使用了这个脚本
function isNumberKey(evt)
{
var e = event || evt; // for trans-browser compatibility
var charCode = e.which || e.keyCode;
if (charCode > 31 && (charCode < 47 || charCode > 57))
return false;
if (e.shiftKey) return false;
return true;
}
But this script not working in firefox alone. Any alternatives to restrict user for shift key in javascript?
但是这个脚本不能单独在 Firefox 中工作。任何限制用户使用 javascript 中的 shift 键的替代方法?
采纳答案by Fabrício Matté
event
is not defined in Firefox, it's breaking your code. Put it after testing for evt
:
event
未在 Firefox 中定义,它会破坏您的代码。测试后放置它evt
:
function isNumberKey(evt)
{
var e = evt || window.event; //window.event is safer, thanks @ThiefMaster
var charCode = e.which || e.keyCode;
if (charCode > 31 && (charCode < 47 || charCode > 57))
return false;
if (e.shiftKey) return false;
return true;
}
Check your error console next time. :)
下次检查您的错误控制台。:)
回答by Kabilan S
Try this code..
试试这个代码..
$(document).keydown(function (e) {
if (e.shiftKey) {
e.preventDefault();
}
});
check the fiddle..
检查小提琴..
回答by Biswajit Chatterjee
U can restrict any key press (a group of them also) by using jQuery
您可以使用 jQuery 限制任何按键(也可以是一组按键)
$(document).ready(function()
{
$('#PHONE_NUMBER').keypress(function(e) {
var a = [];
var k = e.which;
for (i = 48; i < 58; i++)
a.push(i);
a.push(8);
if (!(a.indexOf(k)>=0))
e.preventDefault();
});
});
Where #phone number is the id of the input element and the for loop and push function pushes only allowed characters. 48 to 58 is key values for digits 0-9 on key board
其中#phone number 是输入元素的id,for 循环和push 函数只推送允许的字符。48 到 58 是键盘上数字 0-9 的键值