kennycodes
kennycodes

Reputation: 536

Prevent enter key on html input field react.js

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!

Upvotes: 0

Views: 6511

Answers (2)

Sahil Mahajan Mj
Sahil Mahajan Mj

Reputation: 11141

You 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.
    }

Upvotes: 4

Alexander Shtang
Alexander Shtang

Reputation: 1959

You probably need event.preventDefault() method inside input change method.

Something like:

inputChange = event => {
  if (event.target.key === 'Enter') {
    event.preventDefault();
  }
}

Upvotes: 1

Related Questions