Skip to content

Commit b430c8d

Browse files
author
Dominic Tubach
committed
Allow keys like tab, arrows, or Ctrl in number input fields
1 parent a2aba83 commit b430c8d

File tree

1 file changed

+60
-11
lines changed

1 file changed

+60
-11
lines changed

js/number-input.js

Lines changed: 60 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,34 @@
2626
.formatToParts(1.1)
2727
.find(part => part.type === 'decimal')
2828
.value;
29-
const digits = '0123456789';
29+
30+
const digits = [
31+
'0',
32+
'1',
33+
'2',
34+
'3',
35+
'4',
36+
'5',
37+
'6',
38+
'7',
39+
'8',
40+
'9',
41+
];
42+
43+
const allowedKeys = [
44+
'ArrowDown',
45+
'ArrowLeft',
46+
'ArrowRight',
47+
'ArrowUp',
48+
'Backspace',
49+
'Delete',
50+
'End',
51+
'Enter',
52+
'Home',
53+
'PageDown',
54+
'PageUp',
55+
'Tab',
56+
];
3057

3158
function getElementLang(element) {
3259
if (element.lang) {
@@ -50,23 +77,45 @@
5077
.value;
5178
}
5279

53-
element.addEventListener('keydown', function (event) {
54-
if (event.key === 'Backspace' || '0123456789'.indexOf(event.key) !== -1) {
55-
return;
80+
function isCharAllowed(char) {
81+
if (digits.includes(char)) {
82+
return true;
5683
}
5784

58-
if ('-' === event.key) {
59-
if (element.value.indexOf('-') === -1 && (element.min < 0 || element.min === '' || element.min == null)) {
60-
return;
85+
if ('-' === char) {
86+
if (!element.value.includes('-') && (element.min < 0 || element.min === '' || element.min == null)) {
87+
return true;
6188
}
6289
}
63-
else if (decimalSeparators.indexOf(event.key) !== -1) {
64-
if (element.value.indexOf('.') === -1 && (element.step === 'any' || element.step < 1)) {
65-
return;
90+
else if (decimalSeparators.includes(char)) {
91+
if (!element.value.includes('.') && (element.step === 'any' || element.step < 1)) {
92+
return true;
6693
}
6794
}
6895

69-
event.preventDefault();
96+
return false;
97+
}
98+
99+
element.addEventListener('keydown', function (event) {
100+
if (!event.ctrlKey && !allowedKeys.includes(event.key) && !isCharAllowed(event.key)) {
101+
event.preventDefault();
102+
}
103+
});
104+
105+
element.addEventListener('paste', function (event) {
106+
const data = event.clipboardData.getData('text/plain');
107+
if (data === '') {
108+
event.preventDefault();
109+
return;
110+
}
111+
112+
for (let i = 0; i < data.length; i++) {
113+
if (!isCharAllowed(data[i])) {
114+
event.preventDefault();
115+
116+
return;
117+
}
118+
}
70119
});
71120
});
72121
}

0 commit comments

Comments
 (0)