Skip to content

Commit e877796

Browse files
committed
closes #2641
1 parent e49bc3b commit e877796

File tree

1 file changed

+7
-3
lines changed

1 file changed

+7
-3
lines changed

2-ui/3-event-details/7-keyboard-events/article.md

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -139,12 +139,16 @@ For instance, the `<input>` below expects a phone number, so it does not accept
139139
```html autorun height=60 run
140140
<script>
141141
function checkPhoneKey(key) {
142-
return (key >= '0' && key <= '9') || key == '+' || key == '(' || key == ')' || key == '-';
142+
return (key >= '0' && key <= '9') || ['+','(',')','-'].includes(key);
143143
}
144144
</script>
145145
<input *!*onkeydown="return checkPhoneKey(event.key)"*/!* placeholder="Phone, please" type="tel">
146146
```
147147

148+
The `onkeydown` handler here uses `checkPhoneKey` to check for the key pressed. If it's valid (from `0..9` or one of `+-()`), then it returns `true`, otherwise `false`.
149+
150+
As we know, the `false` value returned from the event handler, assigned using a DOM property or an attribute, such as above, prevents the default action, so nothing appears in the `<input>` for keys that don't pass the test. (The `true` value returned doesn't affect anything, only returning `false` matters)
151+
148152
Please note that special keys, such as `key:Backspace`, `key:Left`, `key:Right`, `key:Ctrl+V`, do not work in the input. That's a side-effect of the strict filter `checkPhoneKey`.
149153

150154
Let's relax it a little bit:
@@ -153,8 +157,8 @@ Let's relax it a little bit:
153157
```html autorun height=60 run
154158
<script>
155159
function checkPhoneKey(key) {
156-
return (key >= '0' && key <= '9') || key == '+' || key == '(' || key == ')' || key == '-' ||
157-
key == 'ArrowLeft' || key == 'ArrowRight' || key == 'Delete' || key == 'Backspace';
160+
return (key >= '0' && key <= '9') ||
161+
['+','(',')','-','ArrowLeft','ArrowRight','Delete','Backspace'].includes(key);
158162
}
159163
</script>
160164
<input onkeydown="return checkPhoneKey(event.key)" placeholder="Phone, please" type="tel">

0 commit comments

Comments
 (0)