Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable form submission via Enter key on only _some fields

I want to retain the conventional 'form submits when i press Enter' behavior because users are familiar with. But by reflex, they often hit enter when they finish with a text input box - but before they are actually done with the complete form.

I'd like to hijack the Enter key only when then focus is on a certain class of input.

Looking Related Questions this looks like 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) { part is unfamiliar to me.

like image 718
justSteve Avatar asked May 08 '10 12:05

justSteve


People also ask

How do I stop form submission on enter key?

$(document). on('keyup keypress', 'form input[type="text"]', function(e) { if(e. keyCode == 13) { e. preventDefault(); return false; } });

How do you prevent form submit on enter key press react?

To prevent form submission when the Enter key is pressed in React, use the preventDefault() method on the event object, e.g. event. preventDefault() . The preventDefault method prevents the browser from refreshing the page when the form is submitted.

How do I disable form fields?

To disable form fields, use the CSS pointer-events property set to “none”.


2 Answers

You can capture and cancel the enter keypress on those fields like this:

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

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

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

$('.noEnterSubmit').bind('keypress', false); 
like image 55
Nick Craver Avatar answered Sep 21 '22 11:09

Nick Craver


 <input type="text"  onkeydown="return (event.keyCode!=13);" /> 
like image 29
stackuser Avatar answered Sep 20 '22 11:09

stackuser