Home > Web Front-end > JS Tutorial > How to Stop a Form from Submitting on ENTER Keypress?

How to Stop a Form from Submitting on ENTER Keypress?

DDD
Release: 2024-11-09 04:17:02
Original
625 people have browsed it

How to Stop a Form from Submitting on ENTER Keypress?

Preventing Form Submission on ENTER Keypress

In web applications, the ENTER key is often used to submit a form. However, sometimes it's desirable to prevent a form from submitting on ENTER keypress. Below are two methods to achieve this:

Method 1: Onkeypress Handler

This method uses the onkeypress event handler on the form. By creating a function that checks whether the pressed key is ENTER (key code 13) and allowing the form submission only if it's not ENTER, we can prevent immediate form submission. The code for this approach is:

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;
}
document.querySelector('form').onkeypress = checkEnter;
Copy after login

Method 2: Event Delegation with Modern JavaScript

A more modern approach using ES20xx and event delegation involves setting a keypress listener on the entire document. This method checks if the form containing the target input has a special attribute indicating that ENTER keypress should submit the form. The relevant JavaScript and HTML code:

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
<form>
Copy after login

Both these methods effectively prevent a form from submitting on ENTER keypress while allowing textarea input, which naturally uses ENTER for line breaks, to function normally.

The above is the detailed content of How to Stop a Form from Submitting 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template