Home »
jQuery »
jQuery Examples
jQuery Disable Form Submit on Enter
In this tutorial, we'll discuss how to disable a form submit when pressing enter key using jQuery?
Submitted by Pratishtha Saxena, on June 23, 2022
jQuery is a JavaScript library used to simplify HTML DOM tree traversal and manipulation, and event handling. It is free, open-source software. It is user-friendly and easy to use.
Note: Always remember to apply the CDN link while working with jQuery.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
The task here is to make sure that the input entered in the textbox of a form should not be submitted if the user is trying to press enter to submit. If the user clicks on the submit button with the mouse only then the input should be submitted.
This is useful when the enter key has other jobs rather than submit. Suppose if enter key is pressed to change the line inside the textbox but instead, it submits the form then we would want to disable the submit button of the form when enter key is pressed. To achieve this, the following method is used.
First and foremost, the form is selected using the selector on which this task has to be performed. Then a function with parameter e is passed upon any keypress. The keypress() method in jQuery implements the specified function when any key is pressed. Once any key is pressed, keypress() triggers the function.
Syntax:
$(selector).keypress();
$(selector).keypress(function);
Now the keyCode is used which will return the Unicode character code of the specified key. For example, 13 is the keycode of Enter.
Syntax:
console.log(event.keyCode);
If the keycode is equal to 13 (here) then we'll have to cancel the event that was going to occur. This can be done using the preventDefault() method of jQuery. This method cancels the particular event. But it can only cancel the events which are cancellable, some events are not cancellable too. No parameters are passed for this.
Syntax:
event.preventDefault();
These all above discussed methods when combined can help disable the submit button of the form when enter key is pressed.
Let's see an example of this.
jQuery Code to Disable Form Submit on Enter
HTML Code:
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<center>
<h2>Enter Text:</h2>
<br>
<form id="myForm">
<input type="text" id="myInputID"><br><br>
<button type="submit" onclick="submit()">Submit</button>
</form>
</center>
</body>
</html>
jQuery Function:
<script>
$('#myForm').on('keypress', function(e) {
var keyCode = e.keyCode;
if (keyCode === 13) {
e.preventDefault();
console.log("You pressed Enter..!!");
}
});
</script>
Output: