Home > Web Front-end > JS Tutorial > How to Prevent Form Submission with the ENTER Key?

How to Prevent Form Submission with the ENTER Key?

Barbara Streisand
Release: 2024-11-07 18:50:03
Original
963 people have browsed it

How to Prevent Form Submission with the ENTER Key?

Prevent Web Form Submission with ENTER Key

Preventing the ENTER keypress from triggering form submission is a common requirement in web development. Here's how you can implement this behavior in a web-based application:

Solution:

To disable form submission upon ENTER keypress while preserving textarea behavior, use the following code:

function checkEnter(e) {
    e = e || event;
    var txtArea = /textarea/i.test((e.target || e.srcElement).tagName);
    return txtArea || (e.keyCode || e.which || e.charCode || 0) !== 13;
}
Copy after login

Then, add a keypress handler to the form:

document.querySelector('form').onkeypress = checkEnter;
Copy after login

Alternative Approach (Modern):

A more modern approach using event delegation is as follows:

document.addEventListener(`keypress`, handle);

function handle(evt) {
    const form = evt.target.closest(`#testForm`);
    if (form) {
        if (evt.target.dataset.enterForSubmit) {
            if (evt.key === `Enter`) {
                evt.preventDefault();
                return logClear(`won't submit "${evt.target.value}"`);
            }
            return true;
        }
    }
}
Copy after login

In this case, HTML elements can be annotated with data-enter-for-submit="1" to selectively allow ENTER-based form submission.

The above is the detailed content of How to Prevent Form Submission with the ENTER Key?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template