Disable submitting a form using the Enter key in only a few fields

I want to keep the normal form when I press Enter, because the users are familiar. But in reflection, they often press the enter button when they finish with an input text box, but before they are completed with the full form.

I would like to capture the Enter key only when the focus is on a particular input class.

Finding Questions Related , Similar to what I'm looking for:

if (document.addEventListener) { document.getElementById('strip').addEventListener('keypress',HandleKeyPress,false); } else { document.getElementById('strip').onkeypress = HandleKeyPress; } 

but the if (document.addEventListener) { is unfamiliar to me.

+66
jquery webforms
May 08 '10 at 12:21
source share
3 answers

You can capture and cancel keypress input in fields like this:

 $('.noEnterSubmit').keypress(function(e){ if ( e.which == 13 ) return false; //or... if ( e.which == 13 ) e.preventDefault(); }); 

Then at your inputs just give them class="noEnterSubmit" :)

Looking ahead, if others find this later, in jQuery 1.4.3 (not yet out) you can shorten it to this:

 $('.noEnterSubmit').bind('keypress', false); 
+127
May 8 '10 at
source share

Just add the following code to the <Head> in your HTML code. He will fill out a key entry application. For all form fields

 <script type="text/javascript"> function stopEnterKey(evt) { var evt = (evt) ? evt : ((event) ? event : null); var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null); if ((evt.keyCode == 13) && (node.type == "text")) { return false; } } document.onkeypress = stopEnterKey; </script> 
+3
May 27 '13 at 11:57
source share

To allow input only in a specific class (in this example, "enterSubmit"):

 jQuery(document).ready(function(){ jQuery('input').keypress(function(event){ var enterOkClass = jQuery(this).attr('class'); if (event.which == 13 && enterOkClass != 'enterSubmit') { event.preventDefault(); return false; } }); }); 
+1
Apr 02 '13 at 4:58
source share



All Articles