Example of accessing input fields with shortcuts in JavaScript
Showcase
When you press 1 on the keyboard, the focus moves to the first input field, and when you press 2, the focus moves to the second input field. As explained in more detail below, when pressing 1 you can see the character “1” being entered directly into the first input field. To prevent this, the second input field uses the event.preventDefault()
method to block the input.
Code
HTML
<label for="input1">첫 번째 입력칸:</label>
<input type="text" id="input1"><br><br>
<label for="input2">두 번째 입력칸:</label>
<input type="text" id="input2"><br><br>
- The
<label>
tag is not an essential element for this example, at least. - The
getElementById().focus()
method in JavaScript operates via theid
attribute of the<input>
tag.
JavaScript
<script>
document.addEventListener("keydown", function(event) {
if (event.key === "1") {
document.getElementById("input1").focus();
} else if (event.key === "2") {
event.preventDefault(); // 2 입력 방지
document.getElementById("input2").focus();
}
});
</script>
- The
"keydown"
first argument ofdocument.addEventListener
causes the event to fire when a key is pressed. - You can change the shortcut keys by modifying the string compared with
event.key
. - Without
event.preventDefault()
, pressing the shortcut key will insert the corresponding character into the input field; this method prevents that. - The
document.getElementById(id).focus()
method gives focus to the element with the specifiedid
.