views:

55

answers:

6

I've got a form that has no submit button and it would be great if the form is still submitted when the user hits the enter key. I've tried adding a hidden submit button, which gives me the desired behavior in Safari, Firefox and Chrome, but the form is still not submitted in IE. Is there a standard way of doing this?

+2  A: 

Tested/cross-browser:

function submitOnEnter(e) {
    var theEvent = e || window.event;
    if(theEvent.keyCode == 13) {
        this.submit;
    }
    return true;
}
document.getElementById("myForm").onkeypress = function(e) { return submitOnEnter(e); }

<form id="myForm">
<input type="text"/>
...
</form>

If there is no submit button, the form will degrade miserably if javascript is not available!

karim79
Shouldn't that be `*on*keypress`?
Andy E
@Andy E - Thanks, indeed it should, fixed :)
karim79
A: 

onKeyDown event of textbox or some control call a javascript function and add form.submit(); statement to the function.

Happy coding!!

Ravia
A: 

Is this what you mean?

document.myformname.submit();
dale
+1  A: 

Using jQuery (naturally):

$("#myForm input").keyup(
    function(event){
        if(event.keycode == 13){
            $(this).closest('form').submit();
        }
    }
);

Give that a try.

inkedmn
Forms are usually submit (on Windows, anyway) when the enter key is pressed down, not lifted up.
Andy E
A: 

This will require JavaScript. The easiest way to implement this with JavaScript if you don't know the language would be to use something like jQuery (much like what inkedmn said).

<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"&gt;&lt;/script&gt;
    <script type="text/javascript" charset="utf-8">
    <!--
        $(document).ready(function() {
            $(document).keyup(function(event){
                if(event.keycode == 13){ // This checks that it was the Enter key
                    $("#myForm").submit(); // #myForm should match the form's id attribute
                }
            });
        });
    //-->
    </script>
</head>
<body>
    <form id="myForm">
    ...
    </form>
</body>

For more information on jQuery: http://docs.jquery.com/Tutorials:How_jQuery_Works#jQuery:_The_Basics

mhost
A: 

You know that you can just put a <button type="submit">submit</button> there and change his position with css, right? position:absolute;left:-9999px; Should do the trick. display:none will not work tho.

This will also work if js is not loaded.

edit: However, if you chose to use js, do not forget to not submit if you have a textarea.

Ionut Staicu
Thanks for the suggestion, but this doesn't work in IE7
Readonly
Works for me... http://iamntz.com/experiments/form_test.php :)
Ionut Staicu