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
Barbara StreisandOriginal
2024-11-07 18:50:03964browse

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;
}

Then, add a keypress handler to the form:

document.querySelector('form').onkeypress = checkEnter;

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;
        }
    }
}

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!

Statement:
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