Open In App

JavaScript - Prevent Users From Submitting a Form by Hitting Enter

Last Updated : 26 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

We can use Onkeydown event attribute for Prevent Users From Submitting a Form by Hitting Enter in JavaScript. It will prevent the submission of form directly.

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.

Syntax

<form id="form-id" onkeydown="if(event.keyCode === 13) {
alert('You have pressed Enter key, use submit button instead');
return false;}">

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
<form id="form-id" onkeydown="if(event.keyCode === 13) {
                alert('You have pressed Enter key, use submit button instead'); 
                return false;
          }">
    <label>First name:</label>
    <input type="text" name="first-name" />
    <div><br />
        <label>Last name:</label>
        <input type="text" name="last-name" />
    </div><br />
    <input type="submit" value="Submit" />
</form>

Output

2. Using the onkeypress Event & preventDefault() 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: This example illustrates preventing the user from submitting a form by hitting Enter Key button by implementing the onkeypress event & the preventDefault() method.

HTML
<form id="gfg">
    <label for="name">
        Name:
    </label>
    <input type="text" name="name" id="name" required>

    <label for="class">
        Class:
    </label>
    <input type="text" name="class" id="class" required>

    <label for="date">
        Enter a date:
    </label>
    <input type="date" name="date" id="date" required>

    <input type="submit" value="Submit" id="btn">
</form>

<script>
    let val = document.getElementById("gfg");
    val.onkeypress = function (key) {
        let btn = 0 || key.keyCode || key.charCode;
        if (btn == 13) {
            alert("Enter Key is Pressed!");
            key.preventDefault();
        }
    } 
</script>

Output


Next Article

Similar Reads