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:
<button/>
, hitting enter won't submit the form.display:none
, positioning them off the page, hiding them inside an overflow:hidden
, or any other method will break the enter-to-submit functionality.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.
I've recently encountered this problem on a client project. How can I implement a fix in a .NET environment, which allows only one form element per page regardless of the number of submit buttons?
Hi,
Interesting to read your article, I had this problem on a site I was developing. It's something that I would probably have just said 'oh well nevermind' but my boss was keen for me to get to the bottom of it and make enter submit the form. I ended up solving the problem and i'm not sure what the problem was, but I think it was due to the fact I had more than 1 form on the page... I think possibly the first form wasn't closed before the second started. However both forms were also hidden so it may be that which caused the problem, however I don't think I put in any javascript solution. I think I just made sure the code was correct and it worked ok...
Tom
Very Interesting ! Tried it out on IE and FireFox . works perfectly. However i realised one more thing .. if u have a select box , and ur focused on it , enter does not submit the form !!!
No reason why .. it doesn't work on IE or Firefox .. works for all other form elements but <select> ...
Strange !!
There is a problem with this solution. If you have a textarea you may need that enter key, as I did, without a form being submitted. My solution is camouflage.
Here is my button:
<input id="subbut" type="submit">
The background color of the form upon which it resides is #80bce0 (not my choice).
Here is my CSS for the button:
input#subbut {
color: #80bce0;
background-color: #80bce0;
border: none;
width: 1px;
height: 1px;
}
The 1px button is not visible on the form. When it was bigger I could see an outline of it when I hit enter which wasn't desirable. Making it really small got rid of that. I know where it is and it is very difficult for me to "accidentally" hit it, though I am able to with perseverance. A user not knowing it was there would have a 1 in 512,000 chance of hitting it on a form 500 pixels high and a 1024x768 pixel resolution. I don't expect anyone will notice it is there.
Tested with IE 6 and Firefox 2.0
For the SELECT issue, the code above wouldn't work, because it's only affecting INPUT tags, but even if you modify it to affect SELECT, it doesn't work. But there's a workaround (ex. using jQuery):
$(function(){
$('select').keydown(function(e){
if (e.keyCode == 13) {
$(':submit').click();
return false;
}
});
});
Instead of calling submit() on the form, you can call click() on the submit button, and it works from a SELECT...
Thanks for this article :) I have found it very useful.
I had the opposite requirement - stopping the ENTER key from automatically submitting the form. As I understand it a good approach (is there a better one?) is a variation on what you have done here.
// using jQuery ...
$(function(){
$('input.field').keydown(function(e){
if (e.keyCode == 13) {
return false;
}
});
});
I ran into a case in which I wanted to submit a form, but process other instructions at the same time, so my solution to add a little more flexibility:
document.body.onkeydown = function(event){
tw_textfieldenter("form.var.something=1;form.submit();", event);
};
//also add firefox/moz based browser compatability
function tw_textfieldenter(stuffToDo,e){
var keycode;
if (window.event) keycode = window.event.keyCode; //ie
else if (e) keycode = e.which; //ff
if (keycode && keycode == 13){
eval(stuffToDo);
return false; //removes ie submit beep
}
}
Given, this assumes that you have a single form on a page. document.body could be replaced with whatever node or input control.
Well the real solution is to have only one submit button on the form, the IE will make it the default... But be aware that most of the time programmers want to have more then one button able to post the form in that case they will have to add javascript to handle the other button (else then the default one)
it's pretty easy once you understand how ie works
There is another wrinkle.
If you are depending on the button name & value being submitted on enter, then you will have problems in IE.
The button name and value are sent only when the button is clicked, otherwise the form is submitted without this information. A workaround I usually do is to have the information I need to be inside hidden fields instead of relying on the button.
I found the form was being submited but the submit filed was not included int the get array. I added a hidden input with the same name as the submit. This will work if javascrit is disabled.
And just for completeness (for us Mac folks), you should also test for charcode '3' as well as '13'. '3' is the ENTER key on a Mac on the numeric pad, which within the context of a FORM will emulate the behaviors of the RET key (charcode 13).
If you have server side scripting tools available, like php, then you could use it to check if the text field was posted containing data and not check solely if the button name itself was posted.
?php
if (!empty($_GET) && $_GET['value_name']) {
// take an action upon success
} else {
//show error msg, ignore request, etc.
}
?>
A great example is a site a friend uses the services of ( http://www.4RemoteSupport.com - www.4RemoteSupport.com ) has two forms on their main page. I inquired as to how they overcame the IE problem of having two forms on the same page and the user hitting the enter key. They were nice enough to reply with some useful information.
I hope this information may help someone with a similar problem. At least it points out that there are additional methods to fix this sort of problem (... I mean feature not problem) besides javascript and CSS.
You would think IE would jump on the band wagon to fix this. It's annoying. Always gotta patch things to make them work with Microsoft~
THANK YOU ISAAC!
I've been pulling my hair out trying to figure out why my search button works in every browser except IE.. and you nailed it right on the head.
Just a little comment here about IE in general. For such a large company as Microsoft to create such a terribly "difficult" browser as IE, is beyond all sense. There is this issue of submit buttons, but also the issue of flash files needing to be activated, then also the php include() function not working on pages with utf-8 encoding, and the list goes on. No wonder I use Firefox and I would recommend everyone to do so.
Jesse, I found your blog entry while looking into this. I noticed only today for the first time that the enter key wasn't submitting if there was more than one input type=text without a submit button.
But I have to question your assertion (and the comments above) about this being an IE-only problem. I find it to be true as well in Firefox 2.0.0.3.
As soon as I add a submit button, or remove the second text field, the submission on enter works again.
Umm, this might sound silly, but I actually DON'T want my form to submit on pressing enter. I find that some people (when not really thinking) press enter to go to the next text input field on the next line, and submit the form accidentally, prematurely. Can anyone tell me how to disable this feature and stop this from happening?
It's not a bug, it's a feature...
http://www.devside.net/blog/linux-windows-bug-feature
I've got one weird situation.
I have a form with two submit buttons. One is delete and another is update. I am using php.
Also I am using $_SERVER['PHP_SELF'], so that it will call itself for update. For form code goes like this.
<input name="update" type="submit" value="Update" />
<input name="delete" type="submit" value="Delete" />
In server side code goes like this
if(isset($_POST['update']))
{
//update
}
if(isset($_POST['delete']))
{
//delete
}
Now: Here is the problem. This code works perfectly in Firefox but not in IE. I even used javascript to submit form instead but it did not worked.
ANY HELP WILL BE GREATLY APPRECIATED.
Carol to stop that from occuring, validate the form. :p
Hey guys,
I find when it comes to forms, its all a matter of opinion. Firstly I use javascript to validate all the fields, alerting if incorrect values are left out. Then I additionally check the value via php, sending them back to the prior page and retaining their original values.
Time consuming, but when you work with databases, bookings, and finnicky things. You need to be carefull.
By the way to stop the enter button working:
//Get the submit, this is important that it points
$submit = $_POST['submit'];
if (isset($submit)){
//code to execute }
<!--THE FORM-->
<form action blah blah>
<input>
<input>
<input type="submit" name="submit" value="submit">
<!-- this form wont submit on enter (with ie) unless there is a
<input type="hidden" value="submit"> -->
but hell who knows?
Thank you Isaac Tewolde,
you gave us the simplest key: In turn of checking on the submit var check on a hidden var included in the form.
when using a password field, i noticed firefox is not activating that "password confirm" window. so i restricted that jquery function just to MSIE.
if($.browser.msie) {
$(function(){
$('input').keydown(function(e){
if (e.keyCode == 13) {
$(this).parents('form').submit();
return false;
}
});
});
}
This info helped me!
Thanks.
/* A tiny improvement / modification if you need the form to be sent also when choosing other fields like select boxes (in firefox it made the form get submitted also for ticking any check box or radio button too!!) all you need to do is to replace the original code presented here by this one: */
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');
var selects= forms[i].getElementsByTagName('select');
for (var j=0;j < inputs.length;j++)
addInputSubmitEvent(forms[i], inputs[j]);
for (var j=0;j < selects.length;j++)
addInputSubmitEvent(forms[i], selects[j]);
}
};
/* thanks for the creator of this code hope this helps others too :)) */
Hey,
I spend my time working around the hidden submit button problem and found a solution that works in both browsers:
<div class="hidesubmit"><input type="submit"></div>
and in the style section/file:
div.hidesubmit {
border: none;
width: 0px;
height: 0px;
overflow: hidden;
}
<input style="border:0; width:0; height:0" type="text" size="0" maxlength="0" />
Add this before input="submit" , and Enter key works in MSIE.
Thanks to the info on this page I solved the problem that was kicking my rear. One one page I had a form with several input fields and a Find and Find All button and when I hit enter it submitted. One the other page I had only one input field and one button and it would not submit. When I looked at the $post_array the text in the input box text was always returned but the "find" value was only returned if I hit the find button. I reduced the code to a few lines and it still had this problem (yes I like the enter button to submit). When I read something about it won't work with only one button (IE6 is really stupid) I just added a hidden button with the same find value and it works in all browsers tested so far so thanks much for the tip!
would not submit with enter key:
<input type="submit" name= "find" value= "Find"/>
adding the hidden field before the find button worked:
<input type="hidden" name="find" /><input type="submit" name= "find" value= "Find">
I have one problem with IE.
In my form i have only one text field and one submit button,
when i enter something in text field and press enter key then it
doesn't submit the form, it just refresh the page. Instead of pressing enter key if i click on submit button it works fine.
I have found the solution for this problem, but i want to know perfect solution for this. Just try it out in IE.
You may have noticed that calling <em>form.submit()</em> in IE doesn't call the code that is located the in the form's <em>onsubmit</em> attribute. Another really cool feature!
To remedy this you need an extra line:
if (e.keyCode == 13) {
$(this).parents('form').attr("onsubmit")();// run onsubmit stuff in IE
$(this).parents('form').trigger('submit');
return false;
}
awesome thanks!
I did as JB (comment #10) did and it works !
Btw, nice workaround. Google takes me right to this blog and my problem solved ^_^
I have found this a problem as ie doen't always include submit in the GET / POST array, and then you may use something like...
if (isset($_GET['submit'])
{
}
I simply check for the submission of compulsary input fields rather than the submit element in any given form.
thanks for the jquery code. works great
My problem was that the "submit" button wasn't being passed.
Many thanks, the javascript functions work great for me.
hi guys
I have been stuck with this issue for 3+ hrs now..can anyone please help?
my page #s on a search results page trigger a function that submits the page's search form.
this is how I generate the page #:
echo ' <a href="javascript:void(0);" onclick="return Paginate('.$i.');">'.$i.'</a>';
where $i is in a loop.
This is the Paginate function
function Paginate(p)
{
//alert("valu " + document.getElementById('formSearch').current_page.value);
var frm = document.getElementById("formSearch");
var btnSubmit = document.getElementById("btnSearch");
frm.current_page.value=p;
//document.formSearch.submit();
frm.submit();
}
My form is declared as:
<form action="main.php" method="post" id="formSearch" name="formSearch">
And the submit button is declared as:
<input name="btnSearch" type="submit" id="btnSearch" value="Search">
(just one submit button).
Now in FF, it works fine. In IE, it seems to call the Paginate function since I can see the popup window (the alert call in the function)...but the form wont submit.
Funny thing is.. you click the page number.. form won't submit immediately.. but you click on another link or the submit button yourself, and it will suddeny show the refreshed page with the new page number.
someone please help with this IE wackkiness ?
thanks guys
I just ran across this oddity...
Anyhoo, IE seems to submit when there's a "submit"-type input, but not when there's an "image"-type input.
Except on a different page, either works. Or doesn't work. Based on my investigation, I think it has something to do with whether or not you've set the clock properly on your VCR. If you're too young to have a VCR, then you're SOL. Sorry kids.
Hi guys,
I found this post very interesting, nice work! But I figured out the 'button' element indeed works on IE6 by simply hitting enter button (with Javascript disabled) even when focus isn't on it. I'm very new on this topic, so I wanted to know if there is any reason that forces you to use the 'input' element instead of using a 'button'?
thank you !
function addInputSubmitEvent(form, input) {
input.onkeydown = function(evt) {
var evt = (evt) ? evt : event
var charCode = (evt.which) ? evt.which : evt.keyCode
if (charCode == 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]);
}
};
Thanks prabhat It is very useful info
so thanks much for the tip!
Thanks, this one works for me on Firefox, IE6 and Ie7
26. Bart at 4:15pm on September 23, 2007
I ended up with
if ($.browser.msie) {
$('input, select').keydown(function(e){
if (e.keyCode == 13) {
$(':submit').click();
return false;
}
});
}
IE doesn't like it when the input type=submit and name=submit.
Quickest solution is to remove name=submit from the submit input, and set up a hidden field with name=submit and the same value of the submit button.
Thank you.. This is very helpful. The page I am working in did not submit login only on IE, while it was working fine in firefox and chrom.
Thanks for the input ... I added an image to my form with the following code:
<input type="image" style="width:0px;height:0px"/>
And "submit on enter" works like a charm.
comment 45 worked for me! Gj!
@ 48.
Thanks, it works in IE, however FF 3.5 displays a string instead of the 0px image, something localized like: Submit Data.
To prevent this, add the alt-attribut e.g. alt="" to it and its fixed for FF as well.
Works great! thanks for the tip.
Thanks! The fact that IE doesn't include the submit button's data in the POST array when you submit the form using enter was breaking my script, and thanks to this entry I fixed it. Thanks!
Good article, but wat i want I found in one of the comments.
How about when user has the option for either hitting the Submit button as well as hitting enter to submit the search form ?
Any ideas on that ?
Works a treat... thanks!
thanks!
Thanks a ton,Jesse Skinner. It works fine on my site. Great job ...
Thank You a lot! prabhat singh's easy solution works great!
add this to your form:
<div style="border:0;width:0;height:0;overflow:hidden;"><input type="submit"/></div>
hi,
encoutered the same problem, though I could fix it by hidding the submit button but does not work with IE6 and maybe more
here is my solution:
/**
* This function parse a form and attach an event on each accurate element so that the form is submitted when the enter key is pressed.
* It is used to allow us to use an image or a link to submit a form, as it fixes the problems with the way browsers handle
* automatic submission of forms when enter key is pressed. These problems are:
* - Mozilla will not submit a form if no submit button is present
* - IE will not submit the form if no visible submit button is present (display:none or visibily:hidden do not work)
*
*/
function submitFormOnKeyPressEnter(someForm) {
for (i=0 ; i<someForm.length ; i++){
if (someForm[i].type == 'text' ||
someForm[i].type == 'radio' ||
someForm[i].type == 'checkbox' ||
someForm[i].type == 'select-one' ||
someForm[i].type == 'password') {
jQuery(someForm[i]).keypress(function(e){
var keycode;
if (window.event) {
keycode = window.event.keyCode;
} else if (e) {
keycode = e.which;
}
if(keycode == "13"){ /* user pressed enter !*/
alert("enter!");
someForm.submit();
}
});
}
}
}
this function is called like this:
submitFormOnKeyPressEnter(document.forms['myFormName']);
tested with mozilla and ie
Unbelievable. Thanks for this post-- spot on, and fixed an issue a team-member discovered in IE8.
To the 2007 comments about focus on SELECT: Hitting enter while a select list has focus has never submitted a form in IE. Probably they allow for better keyboard nav and selecting items..?
-Bronius
Good Solution.. Thank you so much..
I had this same issue with a form that was hidden on page load. I solved it by using javascript to hide the form after page load. Using enter now submits the form in IE 8.
Thanks Harpster. U gave very useful to all.
within the form coding..
<input type="submit" name="login" value="login">
this submit coding never execute in IE browser..
In front of this code..we will use hdiden values..
For example...
<input type="hidden" name="login" value="login">
<input type="submit" name="login" value="login">
Like above that...
Really above all points are very usefull to me..
Thanks lot guys
This was very helpful I was stuck with IE nit submitting my form since jquery was hiding my submit button to apply some styles.
now works perfect. Once more Thank You.
Thanks a lot! It worked flawlessly on IE6, IE8, Firefox 5 and Chrome 12!
Seriously? People still want forms to submit on "enter"? Many here touched on the reasons why you don't want to submit on enter, and those reasons are more valid and hold true than the reasons for using the enter key to submit a form.
Sweet and easy: done same as Jay@48.
Your rule rules, Jesse!
Jquery UI dialog. Inside which is form. Of course dialogs will be hidden by default. No of the solutions with input hidden (66),
input image 48 works for IE8
Thank you for this blog!
Was searching quite long to fix my problem with onenter and IE.
Keep up the good work.