Disabling enter key for form

后端 未结 12 813
深忆病人
深忆病人 2020-12-04 21:07

I have been trying to disable the Enter key on my form. The code that I have is shown below. For some reason the enter key is still triggering the submit. The cod

12条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-04 21:55

    Most of the answers are in jquery. You can do this perfectly in pure Javascript, simple and no library required. Here it is:

    
    

    This code works great because, it only disables the "Enter" keypress action for input type='text'. This means visitors are still able to use "Enter" key in textarea and across all of the web page. They will still be able to submit the form by going to the "Submit" button with "Tab" keys and hitting "Enter".

    Here are some highlights:

    1. It is in pure javascript (no library required).
    2. Not only it checks the key pressed, it confirms if the "Enter" is hit on the input type='text' form element. (Which causes the most faulty form submits
    3. Together with the above, user can use "Enter" key anywhere else.
    4. It is short, clean, fast and straight to the point.

    If you want to disable "Enter" for other actions as well, you can add console.log(e); for your your test purposes, and hit F12 in chrome, go to "console" tab and hit "backspace" on the page and look inside it to see what values are returned, then you can target all of those parameters to further enhance the code above to suit your needs for "e.target.nodeName", "e.target.type" and many more...

提交回复
热议问题