最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Prevent enter key on html input field react.js - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 4

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

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

Something like:

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

评论列表(0)

  1. 暂无评论