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); },
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.
To prevent form submission when the Enter key is pressed in React, use the preventDefault() method on the event object, e.g. event. preventDefault() .
if you use jQuery, its quite simple. Here you go
$(document).keypress( function(event){ if (event.which == '13') { event.preventDefault(); } });
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:
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With