[英]Permit only numbers and “K” character in a input
I have a Javascript function to permit only numbers in a input. 我有一个Javascript函数,仅允许输入数字。
<input name="onlynumbers" type="text" onkeypress="return isNumber(event);">
This is my Javascript function: 这是我的Javascript函数:
function isNumber(e) {
k = (document.all) ? e.keyCode : e.which;
if (k==8 || k==0) return true;
search = /[0-9]/;
n = String.fromCharCode(k);
return search.test(n);
}
But now I need to permit numbers and also "K" character. 但是现在我需要允许数字以及“ K”字符。 I was trying to modify it but I couldn't get it. 我试图对其进行修改,但无法获取。
May you help me please? 你能帮我吗?
Thanks you! 谢谢! :) :)
Add K to search: 将K添加到搜索:
search = /[0-9K]/;
if you also need lowercase k: 如果还需要小写k:
search = /[0-9kK]/;
In terms of getting just numeric keystrokes, I've been using this function which I didn't originally create, but found somewhere: 就仅获取数字按键而言,我一直在使用最初并未创建但在某处发现的该函数:
function blockNonnumericKeystrokes(e) {
if (e.keyCode == '13') {
prorate();
return;
}
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// 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();
}
}
You can use this regex /\\d+|k/i
- That regex accepts k
and K
, if you only want number and uppercase K
then remove the incase sensitive flag i
: /\\d+|k/
您可以使用此正则表达式/\\d+|k/i
该正则表达式接受k
和K
,如果只需要数字和大写K
则删除大小写敏感标志i
: /\\d+|k/
The attribute e.key
is the pressed key 属性e.key
是按下的键
document.querySelector('[name="onlynumbers"]').addEventListener('keypress', function(e) { if (!/\\d+|k/i.test(e.key)) e.preventDefault(); });
<input name="onlynumbers" type="text">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.