Prevent form submission with enter key

I just wrote this nifty little function which works on the form itself...

$("#form").keypress(function(e) {
    if (e.which == 13) {
        var tagName = e.target.tagName.toLowerCase(); 
        if (tagName !== "textarea") {
            return false;
        }
    }
});

In my logic I want to accept carriage returns during the input of a textarea. Also, it would be an added bonus to replace the enter key behavior of input fields with behavior to tab to the next input field (as if the tab key was pressed). Does anyone know of a way to use the event propagation model to correctly fire the enter key on the appropriate element, but prevent form submitting on its press?

13.10.2009 21:39:53
I just realized I was returning false on KeyUp event instead of KeyPress, which does not stop postback. I just thought I would mention this in case anyone was having the same problem I was having.
Kenneth J 6.11.2009 16:54:57
You're missing the trailing )
Robbie Smith 18.08.2014 19:23:08
and the trailing ;
Stack Underflow 13.12.2016 23:09:42
10 ОТВЕТОВ

Set trigger for both the form and the inputs, but when the input events are triggered, stop the propagation to the form by calling the stopPropagation method.

By the way, IMHO, it's not a great thing to change default behaviors to anything any average user is used to - that's what make them angry when using your system. But if you insist, then the stopPropagation method is the way to go.

0
13.10.2009 21:45:20

You can mimic the tab key press instead of enter on the inputs like this:

//Press Enter in INPUT moves cursor to next INPUT
$('#form').find('.input').keypress(function(e){
    if ( e.which == 13 ) // Enter key = keycode 13
    {
        $(this).next().focus();  //Use whatever selector necessary to focus the 'next' input
        return false;
    }
});

You will obviously need to figure out what selector(s) are necessary to focus on the next input when Enter is pressed.

53
16.12.2013 22:47:54
need to add-- return false;
Craig 6.02.2013 17:11:04
I like how you block the whole input with this return false; return false must be moved into condition block. Otherwise return true must be used.
Ben Sinclair 16.12.2013 14:31:49
how can i avoid cursor from focus in readonly inputfields like skipping the readonly fields
Aitazaz Khan 7.06.2015 10:50:32
@AitazazKhan you can use tabindex attributes but I think your cursor will eventually hit it anyways. You could also maybe setup a jQuery event when the readonly input is focused and force focus to another element... Never tried that.
Jake Wilson 8.06.2015 02:28:16
You may find that $(this).nextAll('INPUT').first().focus(); is more suitable than $(this).next().focus();. Try it and see the differences.
Volomike 10.08.2016 05:41:00
РЕШЕНИЕ

Here is a modified version of my function. It does the following:

  1. Prevents the enter key from working on any element of the form other than the textarea, button, submit.
  2. The enter key now acts like a tab.
  3. preventDefault(), stopPropagation() being invoked on the element is fine, but invoked on the form seems to stop the event from ever getting to the element.

So my workaround is to check the element type, if the type is not a textarea (enters permitted), or button/submit (enter = click) then we just tab to the next thing.

Invoking .next() on the element is not useful because the other elements might not be simple siblings, however since DOM pretty much garantees order when selecting so all is well.

function preventEnterSubmit(e) {
    if (e.which == 13) {
        var $targ = $(e.target);

        if (!$targ.is("textarea") && !$targ.is(":button,:submit")) {
            var focusNext = false;
            $(this).find(":input:visible:not([disabled],[readonly]), a").each(function(){
                if (this === e.target) {
                    focusNext = true;
                }
                else if (focusNext){
                    $(this).focus();
                    return false;
                }
            });

            return false;
        }
    }
}
26
14.10.2009 14:20:48
In case it isn't clear, preventEnterSubmit is a handler for the form's keypress event.
Álvaro González 28.01.2013 11:33:23
if you please add support of select as well will be better
Aitazaz Khan 7.06.2015 13:19:19
For some reason, I just can not get this to work. jQuery('#form_id').onkeypress(preventEnterSubmit(e); returns a reference error saying that e can't be found; same with more roundabout methods such as jQuery('#form_id').addEventListener('keypress', preventEnterSubmit(e)); What's missing here?
Kaji 23.02.2018 05:44:56

From a usability point of view, changing the enter behaviour to mimic a tab is a very bad idea. Users are used to using the enter key to submit a form. That's how the internet works. You should not break this.

7
3.02.2011 09:39:19
Not necessarily all the time. If it is clear enough that another field needs to be filled out, then forcing tab is OK. As long as the next field does indeed need to be filled out.
Bryan Field 8.04.2011 19:18:20
Or if you're using barcode scanners, which automatically send an enter key when they're done sending the barcode number.
bestattendance 17.06.2011 00:04:53
And ... Safari uses enter to select when you're trying to select from a list by hand - which is crap, but that's what it does
Ghoti 23.08.2011 17:22:27
he asked us how, not why.
Skwerl 10.02.2012 06:37:56
I agree with point in general, but, this is why i am here ... I have a form that includes addition of a map point and I don't want users who use the postcode search to accidentally submit the form (the map search field is saved as part of the form too, so i can't pull it out entirely), sometimes there are cases where rules need to be broken
Toni Leigh 18.01.2014 09:07:24

The post Enter Key as the Default Button describes how to set the default behaviour for enter key press. However, sometimes, you need to disable form submission on Enter Key press. If you want to prevent it completely, you need to use OnKeyPress handler on tag of your page.

<body OnKeyPress="return disableKeyPress(event)">

The javascript code should be:

<script language="JavaScript">

function disableEnterKey(e)
{
     var key;      
     if(window.event)
          key = window.event.keyCode; //IE
     else
          key = e.which; //firefox      

     return (key != 13);
}

</script>

If you want to disable form submission when enter key is pressed in an input field, you must use the function above on the OnKeyPress handler of the input field as follows:

<input type="text" name="txtInput" onKeyPress="return disableEnterKey(event)">

Source: http://www.bloggingdeveloper.com/post/Disable-Form-Submit-on-Enter-Key-Press.aspx

3
17.05.2012 13:27:24
this is only working solution for me. My case was an edit with auto-fill options and when you chose option you press enter, right? In my case chosen option was not passing to the js function but rather form was submitted. Now I can use google maps api with this little blocking trick. It works for Google Chrome all right too. Thank you.
Yevgeniy Afanasyev 6.07.2018 02:35:18
@YevgeniyAfanasyev I'm glad you find my solution helpful :)
MA9H 8.08.2018 23:11:07

Note that single input forms always get submitted when the enter key is pressed. The only way to prevent this from happening is this:

<form action="/search.php" method="get">
<input type="text" name="keyword" />
<input type="text" style="display: none;" />
</form>
34
20.10.2012 11:44:29
+1 for your tip: single input forms always get submitted when the enter key is pressed.
Vipul 17.07.2013 04:47:08

In my case i wanted to prevent it only in a dinamically created field, and activate some other button, so it was a little bit diferent.

$(document).on( 'keypress', '.input_class', function (e) {
    if (e.charCode==13) {
        $(this).parent('.container').children('.button_class').trigger('click');
        return false;
    }
});

In this case it will catch the enter key on all input's with that class, and will trigger the button next to them, and also prevent the primary form to be submited.

Note that the input and the button have to be in the same container.

0
1.04.2013 08:53:33

The previous solutions weren't working for me, but I did find a solution.

This waits for any keypress, test which match 13, and returns false if so.

in the <HEAD>

function stopRKey(evt) {
  var evt = (evt) ? evt : ((event) ? event : null);
  var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
  if ((evt.which == 13) && (node.type == "text")) {
    return false;
  }
}

document.onkeypress = stopRKey;
0
3.04.2016 01:36:54

I prefer the solution of @Dmitriy Likhten, yet: it only worked when I changed the code a bit:

[...] else 
            { 
             if (focusNext){
                $(this).focus();
                return false; } //  
            }     

Otherwise the script didn't work. Using Firefox 48.0.2

0
4.09.2016 06:50:08

I modified Dmitriy Likhten's answer a bit, works good. Included how to reference the function to the event. note that you don't include () or it will execute. We're just passing a reference.

$(document).ready(function () {
    $("#item-form").keypress(preventEnterSubmit);
});

function preventEnterSubmit(e) {
    if (e.which == 13) {
        var $targ = $(e.target);

        if (!$targ.is("textarea") && !$targ.is(":button,:submit")) {
            var focusNext = false;
            $(this).find(":input:visible:not([disabled],[readonly]), a").each(function () {
                if (this === e.target) {
                    focusNext = true;
                } else {
                    if (focusNext) {
                        $(this).focus();
                        return false;
                    }
                }
            });

            return false;
        }
    }
}
0
17.04.2019 18:43:16