Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disabling enter key for form

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 code is in my head section and seems to be correct from other sources.

disableEnterKey: function disableEnterKey(e){         var key;               if(window.event)             key = window.event.keyCode; //IE         else             key = e.which; //firefox                return (key != 13);     }, 
like image 671
Chris Pinski Avatar asked Apr 12 '11 02:04

Chris Pinski


People also ask

How do I disable enter in form?

Disabling enter key for the formkeyCode === 13 || e. which === 13) { e. preventDefault(); return false; } }); If you want to prevent Enter key for a specific textbox then use inline JS code.

How do you disable enter key in react JS?

To prevent form submission when the Enter key is pressed in React, use the preventDefault() method on the event object, e.g. event. preventDefault() .


2 Answers

if you use jQuery, its quite simple. Here you go

$(document).keypress(   function(event){     if (event.which == '13') {       event.preventDefault();     } }); 
like image 64
Steven Jiang Avatar answered Oct 02 '22 19:10

Steven Jiang


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

<script type="text/javascript"> window.addEventListener('keydown',function(e){if(e.keyIdentifier=='U+000A'||e.keyIdentifier=='Enter'||e.keyCode==13){if(e.target.nodeName=='INPUT'&&e.target.type=='text'){e.preventDefault();return false;}}},true); </script> 

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

like image 27
Tarik Avatar answered Oct 02 '22 17:10

Tarik