![]() |
In this article, we will see how to prevent users from submitting a form by hitting Enter button in JavaScript. Most of the time, we are required to fill out forms of different types and submit them. While submitting a form, either we press the ENTER key or press the SUBMIT button displayed on the screen. If we have to make a customized form where we can only submit the form via SUBMIT button then, the following approach will be used. Approach 1: Using the ‘Onkeydown’ Event attribute The onkeydown event attribute is an HTML attribute that is used to specify the behavior of a web page when a user presses a key on their keyboard. This attribute can be applied to various HTML elements, such as <input>, <textarea>, and <body>, to specify a JavaScript function that will be executed when a key is pressed down. The onkeydown event attribute can be useful for implementing various keyboard-based interactions in web pages, such as keyboard shortcuts, autocomplete, and navigation.
Syntax: <form id="form-id" onkeydown="if(event.keyCode === 13) { alert('You have pressed Enter key, use submit button instead'); return false; }"> Example 1: In this example, the onkeydown event is added to each of the input fields to check if the keyCode of the pressed key is not equal to 13 (Enter key). If it’s not Enter, the user can continue typing. HTML
Output: ![]()
Approach 2: Using the onkeypress Event & preventDefault() Event Method The onkeypress event is used so that whenever the user presses the key, this event will be called. The preventDefault() method is also used to prevent the browser from executing the default action of the selected element. It can prevent the user from processing the request by clicking the link. Example 2: This example illustrates preventing the user from submitting a form by hitting Enter Key button by implementing the onkeypress event & the preventDefault() method. HTML
Output: ![]()
|
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |