[javascript] 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?

This question is related to javascript jquery html webkit forms

The answer is


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().


This is my code:

  $("#txtMessage").on( "keypress", function(event) {
    if (event.which == 13 && !event.shiftKey) {
        event.preventDefault();
        $("#frSendMessage").submit();
    }
    });

You can also simply add onsubmit="return false" to the form code in the page to prevent the default behaviour.

Then hook (.bind or .live) the form's submit event to any function with jQuery in the javascript file.

Here's a sample code to help:

HTML

<form id="search_form" onsubmit="return false">
   <input type="text" id="search_field"/>
   <input type="button" id="search_btn" value="SEARCH"/>
</form>

Javascript + jQuery

$(document).ready(function() {

    $('#search_form').live("submit", function() {
        any_function()
    });
});

This is working as of 2011-04-13, with Firefox 4.0 and jQuery 1.4.3


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

e.preventDefault();

In HTML codes:

<form action="POST" onsubmit="ajax_submit();return false;">
    <b>First Name:</b> <input type="text" name="firstname" id="firstname">
    <br>
    <b>Last Name:</b> <input type="text" name="lastname" id="lastname">
    <br>
    <input type="submit" name="send" onclick="ajax_submit();">
</form>

In Js codes:

function ajax_submit()
{
    $.ajax({
        url: "submit.php",
        type: "POST",
        data: {
            firstname: $("#firstname").val(),
            lastname: $("#lastname").val()
        },
        dataType: "JSON",
        success: function (jsonStr) {
            // another codes when result is success
        }
    });
}

Just adding for easy implementation. You can simply make a form and then make the submit button hidden:

For example:

<form action="submit.php" method="post">
Name : <input type="text" name="test">
<input type="submit" style="display: none;">
</form>

I use now

$("form").submit(function(event){
...
}

At first I added an eventhandler to the submit button which produced an error for me.


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 <input> element with this type of functionality it's as simple as this:

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

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.


Return false to prevent the keystroke from continuing.


I found out today the keypress event is not fired when hitting the Enter key, so you might want to switch to keydown() or keyup() instead.

My test script:

        $('.module input').keydown(function (e) {
            var keyCode = e.which;
            console.log("keydown ("+keyCode+")")
            if (keyCode == 13) {
                console.log("enter");
                return false;
            }
        });
        $('.module input').keyup(function (e) {
            var keyCode = e.which;
            console.log("keyup ("+keyCode+")")
            if (keyCode == 13) {
                console.log("enter");
                return false;
            }
        });
        $('.module input').keypress(function (e) {
            var keyCode = e.which;
            console.log("keypress ("+keyCode+")");
            if (keyCode == 13) {
                console.log("Enter");
                return false;
            }
        });

The output in the console when typing "A Enter B" on the keyboard:

keydown (65)
keypress (97)
keyup (65)

keydown (13)
enter
keyup (13)
enter

keydown (66)
keypress (98)
keyup (66)

You see in the second sequence the 'keypress' is missing, but keydown and keyup register code '13' as being pressed/released. As per jQuery documentation on the function keypress():

Note: as the keypress event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms.

Tested on IE11 and FF61 on Server 2012 R2


Also to maintain accessibility, you should use this to determine your keycode:

c = e.which ? e.which : e.keyCode;

if (c == 13) ...

Try this:

var form = document.formname;

if($(form).length > 0)
{
    $(form).keypress(function (e){
        code = e.keyCode ? e.keyCode : e.which;
        if(code.toString() == 13) 
        {
             formsubmit();
        }
    })
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to webkit

com.apple.WebKit.WebContent drops 113 error: Could not find specified service HTML5 Video autoplay on iPhone What does the shrink-to-fit viewport meta attribute do? Chrome / Safari not filling 100% height of flex parent How to style HTML5 range input to have different color before and after slider? What are -moz- and -webkit-? Video auto play is not working in Safari and Chrome desktop browser Rotate and translate Background color not showing in print preview Blurry text after using CSS transform: scale(); in Chrome

Examples related to forms

How do I hide the PHP explode delimiter from submitted form results? React - clearing an input value after form submit How to prevent page from reloading after form submit - JQuery Input type number "only numeric value" validation Redirecting to a page after submitting form in HTML Clearing input in vuejs form Cleanest way to reset forms Reactjs - Form input validation No value accessor for form control TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"