Submitting a form on ‘Enter’ with jQuery?

Submitting a form on ‘Enter’ with jQuery?

I have a bog-standard login form – an email text field, a password field and a submit button on an AIR project that’s using HTML/jQuery. When I hit Enter on the form, the entire form’s contents vanish, but the form isn’t submitted. Does anyone know if this is a Webkit issue (Adobe AIR uses Webkit for HTML), or if I’ve bunged things up?
I tried:
$(‘.input’).keypress(function (e) {
if (e.which == 13) {
$(‘form#login’).submit();
}
});

But that neither stopped the clearing behavior, or submitted the form. There’s no action associated with the form – could that be the issue? Can I put a javascript function in the action?

Solutions/Answers:

Solution 1:

$('.input').keypress(function (e) {
  if (e.which == 13) {
    $('form#login').submit();
    return false;    //<---- Add this line
  }
});

NOTE: You accepted bendewey’s answer, but it is incorrect with its description of e.preventDefault(). Check out this stackoverflow answer:
event.preventDefault() vs. return false

Essentially, “return false” is the same as calling e.preventDefault and e.stopPropagation().

Solution 2:

In addition to return false as Jason Cohen mentioned. You may have to also preventDefault

e.preventDefault();

Solution 3:

Don’t know if it will help, but you can try simulating a submit button click, instead of directly submitting the form. I have the following code in production, and it works fine:

    $('.input').keypress(function(e) {
        if(e.which == 13) {
            jQuery(this).blur();
            jQuery('#submit').focus().click();
        }
    });

Note: jQuery(‘#submit’).focus() makes the button animate when enter is pressed.

Solution 4:

Return false to prevent the keystroke from continuing.

Solution 5:

Is there any reason you have to hook and test for the enter key?

Couldn’t you simply add a

<input type="submit" /> 

to your form and have it naturally be submitted when enter is pushed? You could even then hook the form’s onsubmit action and call a validation function from there if you wanted…

You could even use the onsubmit as a test to see if your form is being submitted, but it won’t work if you call form.submit().

Solution 6:

Here’s a way to do this as a JQuery plugin (in case you want to re-use the functionality):

$.fn.onEnterKey =
    function( closure ) {
        $(this).keypress(
            function( event ) {
                var code = event.keyCode ? event.keyCode : event.which;

                if (code == 13) {
                    closure();
                    return false;
                }
            } );
    }

Now if you want to decorate an with this type of functionality it’s as simple as this:

$('#your-input-id').onEnterKey(
    function() {
        // Do stuff here
    } );