[英]How to restrict IMEI number to only 15 digits without counting space after 4 digits
I have input field for imei number which should take only 15 digits that should only be numbers. 我为imei数字输入字段,该字段应仅包含15位数字,只能是数字。 Which I have done, my code below takes only 15 digits and leaves a space after 4 digits.
我已经完成了,下面的代码仅需要15位数字,并在4位数字后留一个空格。
But the main problem I am facing here is if you hold any number it will take 18 digits. 但是我在这里面临的主要问题是,如果您持有任何数字,它将需要18位数字。 because when we type fast it is couting spaces also.
因为当我们快速键入时,它也占用空间。 Here is fiddle link to try here
这是在这里尝试的小提琴链接
IMEI IMEI
$(".imei").on('keyup', function() {
var foo = $(this).val().split(" ").join("");
if (foo.length > 0) {
foo = foo.match(new RegExp('.{1,4}', 'g')).join(" ");
}
$(this).val(foo);
});
$(".imei").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
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: Ctrl+C
(e.keyCode == 67 && e.ctrlKey === true) ||
// Allow: Ctrl+X
(e.keyCode == 88 && 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();
}
});
Change keyup
to keypress
: 将
keyup
更改为keypress
:
$(".imei").on('keypress', function() {
keyup
will only fire when you let go of the key, while keypress
will fire every time the key is sent to the input. 仅在释放键时才会触发
keyup
,而每次将键发送到输入时, keypress
都将触发。
Keep the keydown
code as it's used to limit what's allowed. 保留
keydown
代码,因为它用于限制允许的范围。
Updated fiddle: http://jsfiddle.net/1zLwgf66/1/ 更新的提琴: http : //jsfiddle.net/1zLwgf66/1/
The problem with keypress
is that it occurs before the key has been sent to the input. keypress
的问题在于它发生在按键被发送到输入之前。 You can get around this by adding the key to the input before running your code, or waiting until the default code has completed, by adding a simple setTimeout. 您可以通过在运行代码之前将键添加到输入中来解决此问题,或者通过添加简单的setTimeout等到默认代码完成为止。 With setTimeout, you'll have closure issues, so you need to copy
this
: 使用setTimeout时,将遇到关闭问题,因此您需要复制
this
:
$(".imei").on('keypress', function() {
var inp = this;
setTimeout(function() {
var foo = $(inp).val().split(" ").join("");
Updated fiddle: http://jsfiddle.net/1zLwgf66/2/ 更新的提琴: http : //jsfiddle.net/1zLwgf66/2/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.