简体   繁体   中英

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!

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

Something like:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM