I'm trying to focus an input field element whenever the user presses the '/' key. However, once the element is focused, it also adds the '/' key to the input field because it types in the '/' from when I was trying to detect it.
document.addEventListener("keypress", function(event) {
var element = document.getElementById("formInput")
if (event.key == '/') {
element.focus()
element.value = element.value.slice(0, -1)
}
})
I tried slicing the value afterwards but it turns out, the value in the input field doesn't update until it goes out of the function from the event listener.
How would I remove the extra '/' from the input field after the '/' shows up in the input field?
CodePudding user response:
You could use preventDefault
method to prevent the default behavior of the key press, which in this case is adding the '/' character to the input field:
document.addEventListener("keydown", function (event) {
if (event.key === "/") {
event.preventDefault();
document.getElementById("formInput").focus();
}
});
<input type="text" id="formInput" />