Home > Web Front-end > JS Tutorial > body text

How to Prevent Form Submission on Enter Keypress?

Patricia Arquette
Release: 2024-11-08 18:11:02
Original
524 people have browsed it

How to Prevent Form Submission on Enter Keypress?

Preventing Form Submission on ENTER Keypress

In web-based applications, preventing the ENTER key from submitting a form ensures that the form is only submitted when the user explicitly clicks the submit button. This approach enhances the user experience and prevents accidental form submissions.

To prevent the ENTER key from triggering form submission, you can employ the following code snippet:

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

Once you have defined the checkEnter function, you can attach it as a keypress handler to the form:

<form [...] onkeypress="return checkEnter(event)">
Copy after login

Alternatively, you can use the following ES20xx approach:

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

This approach uses event delegation to prevent form submission when the ENTER key is pressed, allowing the user to input multi-line text in textarea elements without triggering submission.

The above is the detailed content of How to Prevent Form Submission on Enter Keypress?. 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