457

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?

default locale
  • 13,035
  • 13
  • 56
  • 62
b. e. hollenbeck
  • 6,493
  • 7
  • 32
  • 47
  • 3
    Do you really have a class="input" attribute on your – NexusRex Jan 10 '12 at 03:57
  • The classes are generated programmatically by a CMS. Other than that, however, scoping it to $('input') would affect every input on the page, regarless of whether I wanted the behavior or not. Sorry it offends your sensibilities. – b. e. hollenbeck Feb 16 '12 at 15:42
  • 16
    Sensibilities not offended in the least. Just thought it might have been an oversight that lead to the problem. Carry on. – NexusRex Feb 22 '12 at 08:15

16 Answers16

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

Check out this stackoverflow answer: event.preventDefault() vs. return false

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

NoBrainer
  • 5,853
  • 1
  • 27
  • 27
175

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

e.preventDefault();
Seb
  • 24,920
  • 5
  • 67
  • 85
bendewey
  • 39,709
  • 13
  • 100
  • 125
84

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.

karim79
  • 339,989
  • 67
  • 413
  • 406
  • 2
    Works great but I had to add "return false;" to prevent double form submission. – code90 Aug 04 '13 at 23:26
  • Working | See a LOT of results like this talking about trigger, sendkey, etc, doh, blah..., but that is the only works to me and really send a click on a button. Not submit(). So, the trick was focus().click() functions in secuence. THANK YOU. – m3nda Dec 16 '14 at 01:58
  • Works, but i had to put this code under: $(document).ready(function() {... – shasi kanth Aug 22 '17 at 08:56
62

Return false to prevent the keystroke from continuing.

Jason Cohen
  • 81,399
  • 26
  • 107
  • 114
31

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

Zack The Human
  • 8,373
  • 7
  • 39
  • 60
  • 1
    Totally agree. My preference would always be to use the native functionality of the browser (inputs of type=submit natively respond to an enter key press) rather than adding further kludged up scripts.. – Aaron Jan 17 '11 at 23:10
  • 1
    Problem is, what if you are doing ajax stuff and there isn't an actual postback to the server, but you want the UI to behave as the user expects? – devlord Oct 25 '12 at 20:46
  • Indeed... I had overlooked the whole `return false;` thing. – devlord Oct 29 '12 at 05:49
16

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
    } );
Viktor Borítás
  • 135
  • 2
  • 11
bvaughn
  • 13,300
  • 45
  • 46
12

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

Jeff Yates
  • 61,417
  • 20
  • 137
  • 189
GERV
  • 121
  • 1
  • 2
5

This is my code:

  $("#txtMessage").on( "keypress", function(event) {
    if (event.which == 13 && !event.shiftKey) {
        event.preventDefault();
        $("#frSendMessage").submit();
    }
    });
Hoàng Vũ Tgtt
  • 1,863
  • 24
  • 8
4

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

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

if (c == 13) ...
Logan Serman
  • 29,447
  • 27
  • 102
  • 141
3

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>
Joem Maranan
  • 150
  • 9
  • @cebirci and what version is your chrome? I tested from laptops to pc and my code just works. Try to download the newest chrome before you mark it down my answer. – Joem Maranan Nov 07 '13 at 08:55
3

I use now

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

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

Viktor Borítás
  • 135
  • 2
  • 11
faebser
  • 139
  • 1
  • 11
2

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

Piemol
  • 857
  • 8
  • 17
1

As it may be late but you can add below line in html:-

<input onkeyup="submitForm(event)" oninput="addTextName(this)" type="text" id="name-val">

and add this on js file

function submitForm(e) {
var keyCode = e.keyCode ? e.keyCode : e.which;
if (keyCode == 13){
    toggleNextScreen();
}

}

keycode 13 means enter

0

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
        }
    });
}
Milad Ghiravani
  • 1,625
  • 23
  • 43
  • 1
    Please don't post identical answers to multiple questions. Post one good answer, then vote/flag to close the other questions as duplicates. If the question is not a duplicate, *tailor your answers to the question.* – Paul Roub Sep 29 '17 at 13:59
  • @PaulRoub my answer have some difference with another. – Milad Ghiravani Sep 29 '17 at 14:01
  • How is this answer different from [this](http://stackoverflow.com/a/46490387) or [this](http://stackoverflow.com/a/46490427)? – Paul Roub Sep 29 '17 at 14:03
  • @PaulRoub I have this problem and first search google for this. That pages, talk about this problem but not simple. When I find best answer, I decided share this on That pages talk about to help users when search this, see my answer on some similar stackoverflow pages. – Milad Ghiravani Sep 29 '17 at 14:09
  • 1
    this answer is not related to the question at all – Zoltán Süle Nov 22 '18 at 09:52
0
$('form#login').keypress(function (e) {
   var keyCode = e.keyCode ? e.keyCode : e.which;       
   if (keyCode == 13) 
   {
      e.preventDefault();
      $('form#login').submit();
      return false; 
   }
});
rsmdh
  • 128
  • 1
  • 2
  • 12
  • 1
    Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Jul 14 '22 at 19:28
-4

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();
        }
    })
}
Pang
  • 9,564
  • 146
  • 81
  • 122
  • 9
    This is mixing jquery with vanilla javascript in an uncomfortable way, and includes a really odd cast which just confuses things – moopet Sep 20 '12 at 18:39