I spent literally hours tracing down this issue in my code where ESC
was clearing the input text only to find that it wasn't my code doing that. I found that ESC
clears the text from <input type="search" />
.
So when I found this, I thought all my problems were solved - only removing type="search"
removes the button to clear the current text from the input. I figured I could restore this with a quick CSS rule, but it had no effect.
-webkit-appearance: searchfield;
So next I tried preventing the action of ESC
on the search field, but was unable to do this with:
evt.preventDefault()
evt.stopPropagation()
evt.stopImmediatePropagation()
-- technically the React equivalent evt.nativeEvent.stopImmediatePropagation()
How can I work around this issue without creating monstrosities in the DOM or in my code reinventing this built-in feature of the browser?
I just ran into this problem. Turns out you need to:
keydown
eventEscape
key was pressedevent.preventDefault()
If you want to retain the default behavior of removing focus from the search field, you'll need to do that manually by calling .blur()
on the search field. The snippet below assumes this is what you want.
<!DOCTYPE html>
<meta charset="utf-8"/>
<p>Type into the search field and press the Escape key</p>
<input
type="search"
onkeydown="
if (event.key === 'Escape') {
event.preventDefault();
this.blur();
}
"
/>
Of course, you don't have to use an inline handler. You can use something like .addEventListener()
on the search field to do something equivalent, but since the asker mentioned they're using React, I assumed they'd prefer an inline solution they can apply via JSX. (You'll need to do the translation from HTML to JSX.)
This solution checks that event.key === 'Escape'
, one of several ways to accomplish this. As of Jun 2022, the KeyboardEvent.key
property is widely supported. (If you need even wider support, there are other properties on KeyboardEvent
you can check like charCode
, keyCode
, which
, etc, but realize several of them are deprecated and/or have caveats you'll need to handle.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With