[javascript] Prevent form submission on Enter key press

I have a form with two text boxes, one select drop down and one radio button. When the enter key is pressed, I want to call my JavaScript function, but when I press it, the form is submitted.

How do I prevent the form from being submitted when the enter key is pressed?

This question is related to javascript forms keypress dom-events enter

The answer is


Use both event.which and event.keyCode:

function (event) {
    if (event.which == 13 || event.keyCode == 13) {
        //code to execute here
        return false;
    }
    return true;
};

A react js solution

 handleChange: function(e) {
    if (e.key == 'Enter') {
      console.log('test');
    }


 <div>
    <Input type="text"
       ref = "input"
       placeholder="hiya"
       onKeyPress={this.handleChange}
    />
 </div>

If you're using jQuery:

$('input[type=text]').on('keydown', function(e) {
    if (e.which == 13) {
        e.preventDefault();
    }
});

Use event.preventDefault() inside user defined function

<form onsubmit="userFunction(event)"> ...

_x000D_
_x000D_
function userFunction(ev) 
{
    if(!event.target.send.checked) 
    {
        console.log('form NOT submit on "Enter" key')

        ev.preventDefault();
    }
}
_x000D_
Open chrome console> network tab to see
<form onsubmit="userFunction(event)" action="/test.txt">
  <input placeholder="type and press Enter" /><br>
  <input type="checkbox" name="send" /> submit on enter
</form>
_x000D_
_x000D_
_x000D_


A jQuery solution.

I came here looking for a way to delay the form submission until after the blur event on the text input had been fired.

$(selector).keyup(function(e){
  /*
   * Delay the enter key form submit till after the hidden
   * input is updated.
   */

  // No need to do anything if it's not the enter key
  // Also only e.which is needed as this is the jQuery event object.
  if (e.which !== 13) {
       return;
  }

  // Prevent form submit
  e.preventDefault();

  // Trigger the blur event.
  this.blur();

  // Submit the form.
  $(e.target).closest('form').submit();
});

Would be nice to get a more general version that fired all the delayed events rather than just the form submit.


So maybe the best solution to cover as many browsers as possible and be future proof would be

if (event.which === 13 || event.keyCode === 13 || event.key === "Enter")

<div class="nav-search" id="nav-search">
        <form class="form-search">
            <span class="input-icon">
                <input type="text" placeholder="Search ..." class="nav-search-input" id="search_value" autocomplete="off" />
                <i class="ace-icon fa fa-search nav-search-icon"></i>
            </span>
            <input type="button" id="search" value="Search" class="btn btn-xs" style="border-radius: 5px;">
        </form>

</div>

<script type="text/javascript">
    $("#search_value").on('keydown', function(e) {
        if (e.which == 13) {
             $("#search").trigger('click');
            return false;
        }
    });
    $("#search").on('click',function(){
        alert('You press enter');
    });
</script>

Detect Enter key pressed on whole document:

$(document).keypress(function (e) {
    if (e.which == 13) {
        alert('enter key is pressed');
    }
});

http://jsfiddle.net/umerqureshi/dcjsa08n/3/


event.key === "Enter"

More recent and much cleaner: use event.key. No more arbitrary number codes!

NOTE: The old properties (.keyCode and .which) are Deprecated.

const node = document.getElementsByClassName("mySelect")[0];
node.addEventListener("keydown", function(event) {
    if (event.key === "Enter") {
        event.preventDefault();
        // Do more work
    }
});

Modern style, with lambda and destructuring

node.addEventListener("keydown", ({key}) => {
    if (key === "Enter") // Handle press
})

Mozilla Docs

Supported Browsers


A little simple

Don't send the form on keypress "Enter":

<form id="form_cdb" onsubmit="return false">

Execute the function on keypress "Enter":

<input type="text" autocomplete="off" onkeypress="if(event.key === 'Enter') my_event()">

Using TypeScript, and avoid multiples calls on the function

let el1= <HTMLInputElement>document.getElementById('searchUser');
el1.onkeypress = SearchListEnter;

function SearchListEnter(event: KeyboardEvent) {
    if (event.which !== 13) {
        return;
    }
    // more stuff
}

A much simpler and effective way from my perspective should be :

function onPress_ENTER()
{
        var keyPressed = event.keyCode || event.which;

        //if ENTER is pressed
        if(keyPressed==13)
        {
            alert('enter pressed');
            keyPressed=null;
        }
        else
        {
            return false;
        }
}

<form id="form1" runat="server" onkeypress="return event.keyCode != 13;">

Add this Code In Your HTML Page...it will disable ...Enter Button..


Below code will add listener for ENTER key on entire page.

This can be very useful in screens with single Action button eg Login, Register, Submit etc.

<head>
        <!--Import jQuery IMPORTANT -->
        <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>

         <!--Listen to Enter key event-->
        <script type="text/javascript">

            $(document).keypress(function (e) {
                if (e.which == 13 || event.keyCode == 13) {
                    alert('enter key is pressed');
                }
            });
        </script>
    </head>

Tested on all browsers.


native js (fetch api)

_x000D_
_x000D_
document.onload = (() => {_x000D_
    alert('ok');_x000D_
    let keyListener = document.querySelector('#searchUser');_x000D_
    // _x000D_
    keyListener.addEventListener('keypress', (e) => {_x000D_
        if(e.keyCode === 13){_x000D_
            let username = e.target.value;_x000D_
            console.log(`username = ${username}`);_x000D_
            fetch(`https://api.github.com/users/${username}`,{_x000D_
                data: {_x000D_
                    client_id: 'xxx',_x000D_
                    client_secret: 'xxx'_x000D_
                }_x000D_
            })_x000D_
            .then((user)=>{_x000D_
                console.log(`user = ${user}`);_x000D_
            });_x000D_
            fetch(`https://api.github.com/users/${username}/repos`,{_x000D_
                data: {_x000D_
                    client_id: 'xxx',_x000D_
                    client_secret: 'xxx'_x000D_
                }_x000D_
            })_x000D_
            .then((repos)=>{_x000D_
                console.log(`repos = ${repos}`);_x000D_
                for (let i = 0; i < repos.length; i++) {_x000D_
                     console.log(`repos ${i}  = ${repos[i]}`);_x000D_
                }_x000D_
            });_x000D_
        }else{_x000D_
            console.log(`e.keyCode = ${e.keyCode}`);_x000D_
        }_x000D_
    });_x000D_
})();
_x000D_
<input _ngcontent-inf-0="" class="form-control" id="searchUser" placeholder="Github username..." type="text">
_x000D_
_x000D_
_x000D_


Override the onsubmit action of the form to be a call to your function and add return false after it, ie:

<form onsubmit="javascript:myfunc();return false;" >

Cross Browser Solution

Some older browsers implemented keydown events in a non-standard way.

KeyBoardEvent.key is the way it is supposed to be implemented in modern browsers.

which and keyCode are deprecated nowadays, but it doesn't hurt to check for these events nonetheless so that the code works for users that still use older browsers like IE.

The isKeyPressed function checks if the pressed key was enter and event.preventDefault() hinders the form from submitting.

  if (isKeyPressed(event, 'Enter', 13)) {
    event.preventDefault();
    console.log('enter was pressed and is prevented');
  }

Minimal working example

JS

function isKeyPressed(event, expectedKey, expectedCode) {
  const code = event.which || event.keyCode;

  if (expectedKey === event.key || code === expectedCode) {
    return true;
  }
  return false;
}

document.getElementById('myInput').addEventListener('keydown', function(event) {
  if (isKeyPressed(event, 'Enter', 13)) {
    event.preventDefault();
    console.log('enter was pressed and is prevented');
  }
});

HTML

<form>
  <input id="myInput">
</form>

https://jsfiddle.net/tobiobeck/z13dh5r2/


Here is how you can do it using JavaScript:

_x000D_
_x000D_
//in your **popup.js** file just use this function 

    var input = document.getElementById("textSearch");
    input.addEventListener("keyup", function(event) {
        event.preventDefault();
        if (event.keyCode === 13) {
            alert("yes it works,I'm happy ");
        }
    });
_x000D_
<!--Let's say this is your html file-->
 <!DOCTYPE html>
    <html>
      <body style="width: 500px">
        <input placeholder="Enter the text and press enter" type="text" id="textSearch"/> 
          <script type="text/javascript" src="public/js/popup.js"></script>
      </body>
    </html>
_x000D_
_x000D_
_x000D_


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

Examples related to keypress

onKeyDown event not working on divs in React How can I listen for keypress event on the whole page? How to handle the `onKeyPress` event in ReactJS? detect key press in python? jQuery Keypress Arrow Keys Submit form on pressing Enter with AngularJS How to trigger an event in input text after I stop typing/writing? How to capture Enter key press? JQuery: detect change in input field Pressing Ctrl + A in Selenium WebDriver

Examples related to dom-events

Detecting real time window size changes in Angular 4 Does Enter key trigger a click event? What are passive event listeners? Stop mouse event propagation React onClick function fires on render How do you Hover in ReactJS? - onMouseLeave not registered during fast hover over iFrame onload JavaScript event addEventListener, "change" and option selection Automatically pass $event with ng-click? JavaScript click event listener on class

Examples related to enter

Excel doesn't update value unless I hit Enter Press enter in textbox to and execute button command Submit form on pressing Enter with AngularJS How to insert a new line in strings in Android Enter triggers button click C#: How to make pressing enter in a text box trigger a button, yet still allow shortcuts such as "Ctrl+A" to get through? Typing the Enter/Return key using Python and Selenium How to detect pressing Enter on keyboard using jQuery? Prevent form submission on Enter key press