[javascript] Disabling enter key for form

I have been trying to disable the Enter key on my form. The code that I have is shown below. For some reason the enter key is still triggering the submit. The code is in my head section and seems to be correct from other sources.

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

        return (key != 13);
    },

This question is related to javascript html window

The answer is


Most of the answers are in jquery. You can do this perfectly in pure Javascript, simple and no library required. Here it is:

<script type="text/javascript">
window.addEventListener('keydown',function(e){if(e.keyIdentifier=='U+000A'||e.keyIdentifier=='Enter'||e.keyCode==13){if(e.target.nodeName=='INPUT'&&e.target.type=='text'){e.preventDefault();return false;}}},true);
</script>

This code works great because, it only disables the "Enter" keypress action for input type='text'. This means visitors are still able to use "Enter" key in textarea and across all of the web page. They will still be able to submit the form by going to the "Submit" button with "Tab" keys and hitting "Enter".

Here are some highlights:

  1. It is in pure javascript (no library required).
  2. Not only it checks the key pressed, it confirms if the "Enter" is hit on the input type='text' form element. (Which causes the most faulty form submits
  3. Together with the above, user can use "Enter" key anywhere else.
  4. It is short, clean, fast and straight to the point.

If you want to disable "Enter" for other actions as well, you can add console.log(e); for your your test purposes, and hit F12 in chrome, go to "console" tab and hit "backspace" on the page and look inside it to see what values are returned, then you can target all of those parameters to further enhance the code above to suit your needs for "e.target.nodeName", "e.target.type" and many more...


For a non-javascript solution, try putting a <button disabled>Submit</button> into your form, positioned before any other submit buttons/inputs. I suggest immediately after the <form> opening tag (and using CSS to hide it, accesskey='-1' to get it out of the tab sequence, etc)

AFAICT, user agents look for the first submit button when ENTER is hit in an input, and if that button is disabled will then stop looking for another.

A form element's default button is the first submit button in tree order whose form owner is that form element.

If the user agent supports letting the user submit a form implicitly (for example, on some platforms hitting the "enter" key while a text field is focused implicitly submits the form), then doing so for a form whose default button has a defined activation behavior must cause the user agent to run synthetic click activation steps on that default button.

Consequently, if the default button is disabled, the form is not submitted when such an implicit submission mechanism is used. (A button has no activation behavior when disabled.)

https://www.w3.org/TR/html5/forms.html#implicit-submission

However, I do know that Safari 10 MacOS misbehaves here, submitting the form even if the default button is disabled.

So, if you can assume javascript, insert <button onclick="return false;">Submit</button> instead. On ENTER, the onclick handler will get called, and since it returns false the submission process stops. Browsers I've tested this with won't even do the browser-validation thing (focussing the first invalid form control, displaying an error message, etc).


The solution is so simple:

Replace type "Submit" with button

<input type="button" value="Submit" onclick="this.form.submit()" />

Just add following code in <Head> Tag in your HTML Code. It will Form submission on Enter Key For all fields on form.

<script type="text/javascript">
    function stopEnterKey(evt) {
        var evt = (evt) ? evt : ((event) ? event : null);
        var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
        if ((evt.keyCode == 13) && (node.type == "text")) { return false; }
    }
    document.onkeypress = stopEnterKey;
</script>

Here's a simple way to accomplish this with jQuery that limits it to the appropriate input elements:

//prevent submission of forms when pressing Enter key in a text input
$(document).on('keypress', ':input:not(textarea):not([type=submit])', function (e) {
    if (e.which == 13) e.preventDefault();
});

Thanks to this answer: https://stackoverflow.com/a/1977126/560114.


this is in pure javascript

_x000D_
_x000D_
        document.addEventListener('keypress', function (e) {_x000D_
            if (e.keyCode === 13 || e.which === 13) {_x000D_
                e.preventDefault();_x000D_
                return false;_x000D_
            }_x000D_
            _x000D_
        });
_x000D_
_x000D_
_x000D_


I checked all the above solutions, they don't work. The only possible solution is to catch 'onkeydown' event for each input of the form. You need to attach disableAllInputs to onload of the page or via jquery ready()

/*
 * Prevents default behavior of pushing enter button. This method doesn't work,
 * if bind it to the 'onkeydown' of the document|form, or to the 'onkeypress' of
 * the input. So method should be attached directly to the input 'onkeydown'
 */
function preventEnterKey(e) {
    // W3C (Chrome|FF) || IE
    e = e || window.event;
    var keycode = e.which || e.keyCode;
    if (keycode == 13) { // Key code of enter button
        // Cancel default action
        if (e.preventDefault) { // W3C
            e.preventDefault();
        } else { // IE
            e.returnValue = false;
        }
        // Cancel visible action
        if (e.stopPropagation) { // W3C
            e.stopPropagation();
        } else { // IE
            e.cancelBubble = true;
        }
        // We don't need anything else
        return false;
    }
}
/* Disable enter key for all inputs of the document */
function disableAllInputs() {
    try {
        var els = document.getElementsByTagName('input');
        if (els) {
            for ( var i = 0; i < els.length; i++) {
                els[i].onkeydown = preventEnterKey;
            }
        }
    } catch (e) {
    }
}

In your form tag just paste this:

onkeypress="return event.keyCode != 13;"

Example

<input type="text" class="search" placeholder="search" onkeypress="return event.keyCode != 13;">

This can be useful if you want to do search when typing and ignoring ENTER.

/// Grab the search term
const searchInput = document.querySelector('.search')
/// Update search term when typing
searchInput.addEventListener('keyup', displayMatches)

You can try something like this, if you use jQuery.

$("form").bind("keydown", function(e) {
   if (e.keyCode === 13) return false;
 });

That will wait for a keydown, if it is Enter, it will do nothing.


try this ^^

$(document).ready(function() {
        $("form").bind("keypress", function(e) {
            if (e.keyCode == 13) {
                return false;
            }
        });
    });

Hope this helps


The better way I found here:

Dream.In.Code

action="javascript: void(0)" or action="return false;" (doesn't work on me)


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 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 window

CMD command to check connected USB devices Get viewport/window height in ReactJS the MySQL service on local computer started and then stopped AngularJS $watch window resize inside directive tkinter: Open a new window with a button prompt window.close() doesn't work - Scripts may close only the windows that were opened by it Send parameter to Bootstrap modal window? How do I insert a JPEG image into a python Tkinter window? Installing Python 2.7 on Windows 8 How do I get the offset().top value of an element without using jQuery?