I have a input field where when the user types in something, a list of options shows up underneath and the user will click on one of the options. The user can also press the Enter key as well. However, if the user were to enter something that is not in the dropdown that pops up and presses enter, my app crashes. I'm wondering if there is a way where I can disable the enter key on the input field so that when someone tries to press it, it just won't do anything.
Note that is in React as well!
Any help would be appreciated!
Thanks!
I have a input field where when the user types in something, a list of options shows up underneath and the user will click on one of the options. The user can also press the Enter key as well. However, if the user were to enter something that is not in the dropdown that pops up and presses enter, my app crashes. I'm wondering if there is a way where I can disable the enter key on the input field so that when someone tries to press it, it just won't do anything.
Note that is in React as well!
Any help would be appreciated!
Thanks!
Share asked Oct 27, 2018 at 17:58 kennycodeskennycodes 5363 gold badges11 silver badges22 bronze badges 1- If you can then upload your code so that one can understand it more accurately – Mihir Commented Oct 27, 2018 at 18:05
2 Answers
Reset to default 4You can use onKeyDown
event of the input field. You can call some method like below,
const onKeyDown = (event) => {
if (event.keyCode === 13) { //13 is the key code for Enter
event.preventDefault()
//Here you can even write the logic to select the value from the drop down or something.
}
You probably need event.preventDefault()
method inside input change method.
Something like:
inputChange = event => {
if (event.target.key === 'Enter') {
event.preventDefault();
}
}