How to prevent ENTER keypress to submit a web form?

user67722 picture user67722 · Feb 25, 2009 · Viewed 248.3k times · Source

How do you prevent an ENTER key press from submitting a form in a web-based application?

Answer

KooiInc picture KooiInc · Feb 25, 2009

[revision 2012, no inline handler, preserve textarea enter handling]

function checkEnter(e){
 e = e || event;
 var txtArea = /textarea/i.test((e.target || e.srcElement).tagName);
 return txtArea || (e.keyCode || e.which || e.charCode || 0) !== 13;
}

Now you can define a keypress handler on the form:
<form [...] onkeypress="return checkEnter(event)">

document.querySelector('form').onkeypress = checkEnter;