Submit a Form in IE with Enter
Usually, you want to be able to submit a form, like a login or search, just by hitting enter. But sometimes it doesn't work.
Firefox will always let you submit any form by pressing Enter, but Internet Explorer is a little bit picky. I figured out a generalised rule of when it won't work:
There is more than one text/password field, but no<input type="submit"/>
or <input type="image"/>
is visible when the page loads.
This rule has the following interesting consequences:
- If you just have a
<button/>
, hitting enter won't submit the form. - Hiding submit buttons by using
display:none
, positioning them off the page, hiding them inside anoverflow:hidden
, or any other method will break the enter-to-submit functionality. - If a form is hidden when the page loads and is displayed using JavaScript, the enter-to-submit will be broken.
It appears that Internet Explorer scans the page at load time and figures out which submit buttons are visible, then attaches the enter-to-submit functionality to those forms.
To fix these scenarios, you can use the following JavaScript:
function addInputSubmitEvent(form, input) { input.onkeydown = function(e) { e = e || window.event; if (e.keyCode == 13) { form.submit(); return false; } }; } window.onload = function() { var forms = document.getElementsByTagName('form'); for (var i=0;i < forms.length;i++) { var inputs = forms[i].getElementsByTagName('input'); for (var j=0;j < inputs.length;j++) addInputSubmitEvent(forms[i], inputs[j]); } };
(Of course, it's better if you use addDOMLoadEvent instead of window.onload
and addEvent instead of onkeydown
.)
If you use jQuery, you can just write:
$(function(){ $('input').keydown(function(e){ if (e.keyCode == 13) { $(this).parents('form').submit(); return false; } }); });
The return false
is rather important in Internet Explorer, because it prevents that beep that you might hear if you hit return. The beep is saying "you can't hit enter here!", but return false
cancels the key press and therefore the browser won't warn.
Update: As Eric Lentz pointed out, my previous code would submit a form when hitting enter in a textarea. I fixed the solution so the onkeydown event is added to <input>
elements only.