Open In App

How to disable form submit on enter button using jQuery ?

Last Updated : 03 Aug, 2021
Like Article

There are two methods to submit a form,

  • Using the “enter” key: When the user press the “enter” key from the keyboard then the form submit. This method works only when one (or more) of the elements in the concerned form have focus.
  • Using the “mouse click”: The user clicks on the “submit” form button.

Approach: First, We need to select the form. This is done using the query selector: $("#form-id") Now, we need to handle the form submission process. For this purpose, we use event handling. Since we need whether the user presses the enter key, we add an event listener on every keypress event: on("keypress", function (event) {} )

This event handler will check every keyboard press, so we require a check on the “enter” key. To accomplish this, we can use the event.keyCode or event.which;

event.keyCode: The “keyCode” property returns the Unicode character code of the key that triggered the keypress event.
event.which: The “which” property returns the keyboard key (or mouse button) that was pressed for the event.
Now, we know that the enter key is pressed, we need to stop the default behavior. To accomplish this, we include a call to the jQuery method preventDefault() to stop the event propagating. preventDefault()

preventDefault(): This method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur.


<!DOCTYPE html> 
        Disable form submission on 
        pressing enter key
        body { 
            display: block; 
            margin-top: 8%; 
        h1 { 
        form {
            display: block; 
            margin: 0 auto;
            text-align: center;
        input {
            margin: 4px;
    <form id="form-id">
        <label>First name:</label>
        <input type="text" name="first-name">
        <br />
        <label>Last name:</label>
        <input type="text" name="last-name">
        <br />
        <input type="submit" value="Submit" />
        $(window).ready(function() {
        $("#form-id").on("keypress", function (event) {
            var keyPressed = event.keyCode || event.which;
            if (keyPressed === 13) {
                alert("You pressed the Enter key!!");
                return false;


jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.
You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads